The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): tie spillover archive lifetime to the owning session (#126351)
liuhao10240d241b124c9d
diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 889e5077c86..6cda829d39d 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -323,6 +323,43 @@ class SessionMaintenanceMixin:self._auto_archive_lineage(row[0])return len(rows)+ def _spillover_refs(self, conn, session_ids) -> set:+ """Spillover archive basenames the to-be-deleted sessions' messages point at. Runs+ INSIDE the delete transaction, before the DELETEs take those messages away, so the+ owning pointers are captured while they still exist (#126351)."""+ from tools.tool_result_storage import spillover_names_in_text+ names: set = set()+ for chunk in _id_chunks(list(session_ids)):+ rows = conn.execute(+ f"SELECT content, api_content FROM messages WHERE session_id IN ({_placeholders(chunk)})"+ " AND (content LIKE '%spillover/%' OR api_content LIKE '%spillover/%')",+ chunk,+ ).fetchall()+ for content, api_content in rows:+ names |= spillover_names_in_text(content, api_content)+ return names++ def _unlink_dead_spillover(self, names: set) -> None:+ """After the delete transaction committed: remove the archives whose owning messages+ just went away and that no surviving session references — a spill referenced by a+ retained session stays available exactly as long as that session does (#126351).+ Best-effort: any read/unlink hiccup leaves the file to the hourly orphan sweep."""+ if not names:+ return+ from tools.tool_result_storage import referenced_spillover_names+ try:+ spill_dir = self.db_path.parent / "cache" / "spillover"+ referenced = referenced_spillover_names(spill_dir)+ if referenced is None: # unknown reference set: fail closed, keep the files+ return+ for name in names - referenced:+ try:+ (spill_dir / name).unlink(missing_ok=True)+ except OSError as exc:+ logger.debug("Spillover unlink failed for %s: %s", name, exc)+ except Exception as exc:+ logger.debug("Spillover cleanup after session delete failed: %s", exc)+def prune_sessions(self, older_than_days: Optional[float] = 90, source: str | None = None,sessions_dir: Optional[Path] = None, exclude_active_write_guards: bool = False,deleted_ids: Optional[list] = None, **filters) -> int:@@ -337,6 +374,7 @@ class SessionMaintenanceMixin:in-memory routes and live sessions after the commit."""where, where_params = self._prune_where(older_than_days, source, filters, whole_lineages=True)removed_ids: list[str] = []+ spillover_names: set = set()def _do(conn):cursor = conn.execute(f"SELECT s.id FROM sessions s WHERE {where}", where_params)session_ids = {row["id"] for row in cursor.fetchall()}@@ -347,6 +385,7 @@ class SessionMaintenanceMixin:prune_retired_tombstones(conn) # every prune pass also reclaims expired deletion tombstonesif not session_ids:return 0+ spillover_names.update(self._spillover_refs(conn, session_ids))# Batched: a cron-heavy store prunes tens of thousands of ids in one call.for chunk in _id_chunks(session_ids):ph = _placeholders(chunk)@@ -363,6 +402,7 @@ class SessionMaintenanceMixin:self._remove_session_files(sessions_dir, sid)if deleted_ids is not None:deleted_ids.extend(removed_ids)+ self._unlink_dead_spillover(spillover_names)return countdef _page_pragmas(self, names: tuple[str, ...], fail_msg: str) -> Optional[list]:diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 5fc8f6b1497..2701057814e 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -1718,6 +1718,7 @@ class SessionSessionsMixin:include_compression_chain=True,) > 0removed_ids: list[str] = []+ spillover_names: set = set()expected_ids = set(expected_delete_ids) if expected_delete_ids is not None else Nonedef _do(conn):if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None:@@ -1742,6 +1743,8 @@ class SessionSessionsMixin:for covered_id, expected in expected_display_messages.items()):return False+ # Capture the doomed messages' spillover pointers before the DELETEs (#126351).+ spillover_names.update(self._spillover_refs(conn, target_ids or [*scope, *_collect_delegate_child_ids(conn, scope)]))from hermes_state_mutation_retirement import retire_sessionsretire_sessions(conn, scope)removed_ids.extend(_delete_delegate_children(conn, scope))@@ -1757,6 +1760,7 @@ class SessionSessionsMixin:collect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)+ self._unlink_dead_spillover(spillover_names)return bool(deleted)def discard_unadmitted_session(self, session_id: str) -> bool:@@ -1838,6 +1842,7 @@ class SessionSessionsMixin:if not unique_ids:return 0removed_ids: list[str] = []+ spillover_names: set = set()def _do(conn):existing = [row["id"] for chunk in _id_chunks(unique_ids) for row in conn.execute(f"SELECT id FROM sessions WHERE id IN ({_session_ids_placeholders(chunk)})", chunk,@@ -1884,6 +1889,9 @@ class SessionSessionsMixin:expanded = expand(existing)from hermes_state_mutation_retirement import retire_sessionsretire_sessions(conn, expanded)+ # Capture the doomed messages' spillover pointers before the DELETEs (#126351).+ spillover_names.update(self._spillover_refs(+ conn, [*expanded, *_collect_delegate_child_ids(conn, expanded)]))removed_ids.extend(_delete_delegate_children(conn, expanded))for chunk in _id_chunks(expanded):ph = _session_ids_placeholders(chunk)@@ -1903,6 +1911,7 @@ class SessionSessionsMixin:collect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)+ self._unlink_dead_spillover(spillover_names)return count# Shared by count_empty_sessions / delete_empty_sessions so badge and sweep agree. message_countdiff --git a/tests/test_session_spillover_cleanup.py b/tests/test_session_spillover_cleanup.pynew file mode 100644index 00000000000..904690c377b--- /dev/null+++ b/tests/test_session_spillover_cleanup.py@@ -0,0 +1,172 @@+"""Session-tied spillover unlinking (#126351): an archive referenced by a retained session+stays available exactly as long as that session does.++Two halves under test:+- the age sweep (``cleanup_spillover_cache``) never deletes a referenced archive, and fails+ closed (keeps files) when the reference set is unreadable;+- ``delete_session`` / ``delete_sessions`` / ``prune_sessions`` capture the doomed messages'+ pointers inside the delete transaction and unlink the archives afterwards — but only once no+ SURVIVING session references them (branch/compression siblings may share the pointer)."""++import os+import time++import pytest++from hermes_state import SessionDB+from tools.tool_result_storage import (+ _build_persisted_message,+ cleanup_spillover_cache,+ referenced_spillover_names,+)++THREE_DAYS_S = 3 * 86400++[email protected](autouse=True)+def _home(tmp_path, monkeypatch):+ """One scratch home per test: state.db at the root, spillover under cache/ — the same+ layout ``referenced_spillover_names`` derives from the spill dir."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ import tools.tool_result_storage as trs+ monkeypatch.setattr(trs, "_spillover_pruned_homes", set())+ return tmp_path+++def _spill(home, name, age_hours=0.0):+ spill_dir = home / "cache" / "spillover"+ spill_dir.mkdir(parents=True, exist_ok=True)+ path = spill_dir / name+ path.write_text("archived tool result", encoding="utf-8")+ if age_hours:+ stale = time.time() - age_hours * 3600+ os.utime(path, (stale, stale))+ return path+++def _pointer(home, name, size=150_000):+ return _build_persisted_message(+ preview="preview", has_more=True, original_size=size,+ file_path=str(home / "cache" / "spillover" / name))+++def _aged_session(db, sid, name, ended=True):+ db.create_session(sid, "cli")+ db.append_message(sid, "tool", _pointer(db.db_path.parent, name), timestamp=time.time() - THREE_DAYS_S)+ if ended:+ db.end_session(sid, "completed")+ db._write_sql(+ "UPDATE sessions SET started_at = ?, last_activity_at = ? WHERE id = ?",+ (time.time() - THREE_DAYS_S, time.time() - THREE_DAYS_S, sid))+++def test_retained_sessions_spill_survives_the_age_sweep(_home):+ """The blocking scenario from the review: ``retention_days: 2`` (48h window), the spill is+ 49h old, yet the session that references it was active an hour ago and is retained — the+ sweep must not strand the transcript pointer."""+ db = SessionDB(db_path=_home / "state.db")+ try:+ db.create_session("s_recent", "cli")+ db.append_message("s_recent", "tool", _pointer(_home, "recent.txt"))+ db.end_session("s_recent", "completed") # ended, unpinned, active 1h ago: not prunable+ db._write_sql("UPDATE sessions SET last_activity_at = ? WHERE id = ?",+ (time.time() - 3600, "s_recent"))+ aged = _spill(_home, "recent.txt", age_hours=49)++ assert db.prune_sessions(older_than_days=2) == 0 # session retained...+ assert cleanup_spillover_cache(max_age_hours=48) == 0 # ...so the sweep keeps the archive+ assert aged.exists()+ finally:+ db.close()+++def test_prune_sessions_unlinks_the_spill_with_its_session(_home):+ db = SessionDB(db_path=_home / "state.db")+ try:+ _aged_session(db, "s_old", "dead.txt")+ aged = _spill(_home, "dead.txt", age_hours=72)++ assert db.prune_sessions(older_than_days=2) == 1+ assert not aged.exists()+ finally:+ db.close()+++def test_delete_session_unlinks_the_spill(_home):+ db = SessionDB(db_path=_home / "state.db")+ try:+ _aged_session(db, "s_del", "del.txt")+ spill = _spill(_home, "del.txt")++ assert db.delete_session("s_del") is True+ assert not spill.exists()+ finally:+ db.close()+++def test_delete_sessions_bulk_unlinks_the_spill(_home):+ db = SessionDB(db_path=_home / "state.db")+ try:+ _aged_session(db, "s_a", "bulk_a.txt")+ _aged_session(db, "s_b", "bulk_b.txt")+ a = _spill(_home, "bulk_a.txt")+ b = _spill(_home, "bulk_b.txt")++ assert db.delete_sessions(["s_a", "s_b"]) == 2+ assert not a.exists() and not b.exists()+ finally:+ db.close()+++def test_shared_pointer_survives_until_the_last_session_dies(_home):+ """Branch/compression siblings can share one archive: deleting one holder must not+ strand the other's pointer."""+ db = SessionDB(db_path=_home / "state.db")+ try:+ _aged_session(db, "s_first", "shared.txt")+ _aged_session(db, "s_second", "shared.txt")+ shared = _spill(_home, "shared.txt")++ db.delete_session("s_first")+ assert shared.exists() # s_second still references it++ db.delete_session("s_second")+ assert not shared.exists()+ finally:+ db.close()+++def test_unreferenced_spill_still_sweeps_by_age(_home):+ db = SessionDB(db_path=_home / "state.db")+ try:+ db.create_session("s_alive", "cli") # a live db with no spillover references+ orphan = _spill(_home, "orphan.txt", age_hours=49)++ assert cleanup_spillover_cache(max_age_hours=48) == 1+ assert not orphan.exists()+ finally:+ db.close()+++def test_unreadable_db_fails_closed_keeps_files(_home):+ """A damaged state.db must pause the sweep, not guess: every aged file stays."""+ (_home / "state.db").write_bytes(b"this is not a sqlite database" * 100)+ aged = _spill(_home, "unknowable.txt", age_hours=49)++ assert referenced_spillover_names(_home / "cache" / "spillover") is None+ assert cleanup_spillover_cache(max_age_hours=48) == 0+ assert aged.exists()+++def test_nonfinite_retention_falls_back_and_still_sweeps(_home):+ """YAML ``.inf`` / ``.nan`` used to raise out of ``_spillover_retention_hours`` after the+ once-per-home flag was set — every later sweep silently skipped. Fallback cleanup must+ actually remove a stale file."""+ import yaml++ with (_home / "config.yaml").open("w", encoding="utf-8") as fh:+ yaml.safe_dump({"sessions": {"retention_days": float("inf")}}, fh)+ aged = _spill(_home, "pre_inf.txt", age_hours=49)++ assert cleanup_spillover_cache() == 1 # .inf → 24h fallback → the 49h orphan goes+ assert not aged.exists()diff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex 7dfbf3f6b94..36e53414175 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -212,14 +212,14 @@ class TestBuildPersistedMessage:assert "..." in msg # has_more indicatordef test_message_conditions_the_do_not_rerequest_promise(self):- """#126351: the pointer must not promise the file forever — spill files are- pruned after the session retention window, and the notice says what to do."""+ """#126351: the pointer must not promise the file forever, and the recovery line+ must never tell the model to blindly re-run the producing tool — that call may+ have been a mutation whose effect already landed."""msg = _build_persisted_message(preview="preview", has_more=True, original_size=50_000,file_path="/tmp/hermes-results/test123.txt")- assert "retention" in msg- assert "pruned" in msg- assert "re-run the original tool" in msg+ assert "re-run the original tool" not in msg+ assert "inspect the current state before retrying" in msg# ── maybe_persist_tool_result ─────────────────────────────────────────@@ -565,6 +565,17 @@ class TestSpillover:lambda: {"sessions": {"retention_days": 0}})assert trs._spillover_retention_hours() == trs.SPILLOVER_MAX_AGE_HOURS+ # YAML ``.inf`` / ``.nan`` parse as floats; int() on them raises and used to+ # silently kill every sweep after the once-per-home flag was set.+ monkeypatch.setattr(+ hermes_cli.config, "load_config_readonly",+ lambda: {"sessions": {"retention_days": float("inf")}})+ assert trs._spillover_retention_hours() == trs.SPILLOVER_MAX_AGE_HOURS+ monkeypatch.setattr(+ hermes_cli.config, "load_config_readonly",+ lambda: {"sessions": {"retention_days": float("nan")}})+ assert trs._spillover_retention_hours() == trs.SPILLOVER_MAX_AGE_HOURS+def test_cleanup_missing_dir_returns_zero(self):assert cleanup_spillover_cache() == 0diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex d99544ffdb1..aa2c7f4ce4b 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -8,9 +8,11 @@ else a copy in the sandbox temp dir; (3) ``enforce_turn_budget``."""import hashlibimport jsonimport logging+import mathimport osimport reimport shlex+import sqlite3import tempfileimport threadingimport time@@ -52,6 +54,8 @@ def _spillover_retention_hours() -> int:try:from hermes_cli.config import load_config_readonlydays = float((load_config_readonly().get("sessions") or {}).get("retention_days", 90))+ if not math.isfinite(days): # YAML ``.inf`` / ``.nan`` parse as floats; int() would raise+ return SPILLOVER_MAX_AGE_HOURSexcept Exception:return SPILLOVER_MAX_AGE_HOURS# ``retention_days: 0`` is legal (ended sessions pruned at once) but session prune never@@ -60,14 +64,64 @@ def _spillover_retention_hours() -> int:return max(SPILLOVER_MAX_AGE_HOURS, int(days * 24))+# How a spill archive is named inside transcript text: every pointer form — the host path,+# the ``~``-relative translation, the in-container mounted path — carries the ``spillover/<name>``+# segment. Sandbox-fallback pointers (``…/hermes-results/<name>``) do not, so their host-side+# original stays unreferenced and is reclaimed by the orphan sweep, never by ownership.+_SPILLOVER_NAME_RE = re.compile(r"spillover/([A-Za-z0-9_.-]+)")+++def spillover_names_in_text(*texts) -> set:+ """Spillover archive basenames referenced by transcript message text (empty set on none)."""+ names: set = set()+ for text in texts:+ if isinstance(text, str) and "spillover/" in text:+ names.update(_SPILLOVER_NAME_RE.findall(text))+ return names+++def referenced_spillover_names(spill_dir) -> set | None:+ """Basenames under *spill_dir* still referenced by any message in the home's ``state.db``.++ ``set()`` when no database exists (no sessions → nothing references anything), ``None``+ when the reference set is UNKNOWN (unreadable / truncated query) so callers fail closed+ and keep the files; a plain read-only connection is enough, the write path owns the locks."""+ db_path = spill_dir.parent.parent / "state.db"+ if not db_path.exists():+ return set()+ try:+ # as_uri(): a plain f"file:{path}" breaks on Windows drive letters+ conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True, timeout=5.0)+ try:+ rows = conn.execute(+ "SELECT content, api_content FROM messages "+ "WHERE content LIKE '%spillover/%' OR api_content LIKE '%spillover/%' "+ "LIMIT 20001"+ ).fetchall()+ finally:+ conn.close()+ except Exception:+ return None+ if len(rows) > 20000: # truncated reference set: treat as unknown, never guess+ return None+ names: set = set()+ for content, api_content in rows:+ names |= spillover_names_in_text(content, api_content)+ return names++def cleanup_spillover_cache(max_age_hours: int | None = None) -> int:"""Delete spillover files older than *max_age_hours*; returns count removed (samecontract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop runs hourly).A ``None`` age means the session retention window, not a cache TTL — an explicit- ``max_age_hours`` (tests, legacy callers) still wins."""+ ``max_age_hours`` (tests, legacy callers) still wins. An expired file is deleted only+ when no message in the home's state.db references it: the transcript's+ ``<persisted-output>`` promise outlives the archive's mtime exactly as long as the+ owning session does (#126351) — referenced archives leave with their session, via the+ unlink SessionDB delete/prune performs, not with the age sweep."""age_hours = _spillover_retention_hours() if max_age_hours is None else max_age_hourscutoff = time.time() - (age_hours * 3600)- removed = 0+ expired = []try:entries = list(get_spillover_dir().iterdir())except OSError:@@ -75,8 +129,19 @@ def cleanup_spillover_cache(max_age_hours: int | None = None) -> int:for f in entries:try:if f.is_file() and f.stat().st_mtime < cutoff:- f.unlink()- removed += 1+ expired.append(f)+ except OSError:+ pass+ if not expired:+ return 0+ referenced = referenced_spillover_names(get_spillover_dir())+ removed = 0+ for f in expired:+ if referenced is None or f.name in referenced: # unknown set: fail closed, keep+ continue+ try:+ f.unlink()+ removed += 1except OSError:passreturn removed@@ -294,9 +359,9 @@ def _build_persisted_message(preview: str, has_more: bool, original_size: int,"Use the read_file tool with offset and limit to access specific sections of this output.\n""Recovery: page through the saved file with read_file (offset/limit) or ""process it with execute_code — do NOT re-request the same data from the "- "remote API while the file exists; it is kept for the session retention "- "window, and if it has since been pruned, re-run the original tool to "- "regenerate the output.\n\n"+ "remote API; the archive is kept while this session's transcript references "+ "it. If it is missing, inspect the current state before retrying — the call "+ "that produced it may already have taken effect.\n\n"f"Preview (first {len(preview)} chars):\n"+ preview + ("\n..." if has_more else "")+ f"\n{PERSISTED_OUTPUT_CLOSING_TAG}")diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex f415a95fbe4..53381479d61 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -923,7 +923,7 @@ tool_output:### Tool-Result Spillover Budget-Separately from truncation, oversized tool *results* are spilled to disk rather than cut: the full output is saved under `$HERMES_HOME/cache/spillover/` and the in-context content is replaced by a preview plus the saved file's path (readable with `read_file` using `offset`/`limit`, or processable with `execute_code`). The generic per-result spillover threshold is 100,000 chars, scaled down automatically for small-context models. Spill files are kept for the session retention window (`sessions.retention_days`, default 90 days, never less than 24 hours) so a session resumed later still finds what its transcript points at; the gateway's hourly housekeeping and the first spill of each process sweep older files.+Separately from truncation, oversized tool *results* are spilled to disk rather than cut: the full output is saved under `$HERMES_HOME/cache/spillover/` and the in-context content is replaced by a preview plus the saved file's path (readable with `read_file` using `offset`/`limit`, or processable with `execute_code`). The generic per-result spillover threshold is 100,000 chars, scaled down automatically for small-context models. A spill file is kept as long as any session's transcript still points at it, and leaves with its session when that session is deleted or pruned; the gateway's hourly housekeeping and the first spill of each process only sweep unreferenced files older than the session retention window (`sessions.retention_days`, default 90 days, never less than 24 hours), so a session resumed later still finds what its transcript points at.MCP tool results (tools named `mcp_*`) spill at a tighter **50,000-char** default: MCP servers routinely return large un-paginated payloads (tool-discovery catalogs, batched executions) that would otherwise sit under the generic threshold and bloat context on every subsequent turn. Nothing is lost — the full result is preserved on disk. Override the threshold via: