Skip to content

The agent that grows with you

fix(sessions): Desktop resume of a heavily-compacted chat no longer fails with 4130

Teknium52f359a011e8
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 09aed5ed3ef..ae5ce2a3e5f 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -646,29 +646,16 @@ class CLIAgentSetupMixin:
if not self._session_db:
return None
from hermes_state import (
- SessionExportTooLargeError,
SessionResumeTooLargeError,
- resolved_max_resume_messages,
)
try:
+ safety_check = getattr(self._session_db, "assert_resume_safe", None)
+ if not callable(safety_check):
+ return None
if tip_only:
- tip_check = getattr(self._session_db, "assert_export_safe", None)
- if not callable(tip_check):
- return None
- limit = resolved_max_resume_messages()
- if limit <= 0:
- return None
- try:
- tip_check(self.session_id, max_messages=limit)
- except SessionExportTooLargeError as exc:
- raise SessionResumeTooLargeError(
- exc.message_count, limit, scope="in its tip segment"
- ) from exc
+ safety_check(self.session_id, tip_only=True)
else:
- safety_check = getattr(self._session_db, "assert_resume_safe", None)
- if not callable(safety_check):
- return None
safety_check(self.session_id)
except SessionResumeTooLargeError as exc:
return str(exc)
diff --git a/hermes_state.py b/hermes_state.py
index 2ca8b61fca9..7c1cf4eaa65 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -13597,11 +13597,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
halves the resume's DB work versus two separate calls, with byte-identical
output (see test_get_resume_conversations_matches_separate_reads).
"""
- session_ids = (
- [session_id]
- if self._is_explicit_branch_session(session_id)
- else self._session_lineage_root_to_tip(session_id)
- )
+ session_ids = self._resume_lineage_ids(session_id)
with self._read_ctx() as conn:
placeholders = ",".join("?" for _ in session_ids)
rows = conn.execute(
@@ -13637,9 +13633,32 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
return model_history, display_history
- def get_resume_message_count(self, session_id: str) -> int:
- """Count active rows that a full resume would materialize."""
- session_ids = self._session_lineage_root_to_tip(session_id)
+ def _resume_lineage_ids(self, session_id: str) -> List[str]:
+ """Session ids a full (display) resume materializes for *session_id*.
+
+ Compression continuations need their ended ancestors' rows for the
+ display transcript; an explicit ``/branch`` copy already owns its
+ transcript, so its lineage is itself alone. This is the ONE definition
+ shared by the resume readers (``get_resume_conversations``,
+ ``get_ancestor_display_prefix``) and the resume guard
+ (``assert_resume_safe`` / ``get_resume_message_count``) — the guard must
+ count exactly the rows a resume would load, never a superset.
+ """
+ if self._is_explicit_branch_session(session_id):
+ return [session_id]
+ return self._session_lineage_root_to_tip(session_id)
+
+ def get_resume_message_count(
+ self, session_id: str, *, tip_only: bool = False
+ ) -> int:
+ """Count active rows that a resume would materialize.
+
+ ``tip_only=True`` counts only the tip segment — the set a model-history
+ restore loads (``get_messages_as_conversation`` without ancestors, or
+ the deferred Desktop resume that pages the display transcript over
+ REST and never materializes the ancestor prefix in memory).
+ """
+ session_ids = [session_id] if tip_only else self._resume_lineage_ids(session_id)
placeholders = ",".join("?" for _ in session_ids)
with self._read_ctx() as conn:
row = conn.execute(
@@ -13653,12 +13672,24 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
self,
session_id: str,
max_messages: Optional[int] = None,
+ *,
+ tip_only: bool = False,
) -> int:
"""Return resume row count or reject a transcript too large to load.
``max_messages=None`` resolves the limit from config
(``sessions.max_resume_messages``); 0 disables the guard and returns
the (bounded) count without raising.
+
+ ``tip_only=True`` bounds only the tip segment, for callers that never
+ materialize the ancestor lineage in memory (tip-only model restore,
+ deferred Desktop resume whose display history is REST-paginated). A
+ heavily-compressed conversation — 85 compaction segments and ~29k
+ lineage rows behind a ~700-row tip — is exactly the shape compression
+ is supposed to produce; counting its whole lineage against a limit
+ sized for in-memory materialization rejected the healthiest sessions
+ (Desktop Bot Chat stuck on "Waking up…" with code 4130) while the
+ process would only ever have held the tip.
"""
if max_messages is None:
max_messages = resolved_max_resume_messages()
@@ -13670,7 +13701,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# return value, and an unbounded lineage COUNT here would do the
# exact pathological work the disable exists to avoid.
return 0
- session_ids = self._session_lineage_root_to_tip(session_id)
+ session_ids = [session_id] if tip_only else self._resume_lineage_ids(session_id)
placeholders = ",".join("?" for _ in session_ids)
with self._read_ctx() as conn:
row = conn.execute(
@@ -13682,7 +13713,11 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
).fetchone()
message_count = int(row[0] if row else 0)
if message_count > max_messages:
- raise SessionResumeTooLargeError(message_count, max_messages)
+ raise SessionResumeTooLargeError(
+ message_count,
+ max_messages,
+ scope="in its tip segment" if tip_only else "across its lineage",
+ )
return message_count
def assert_export_safe(
@@ -13741,10 +13776,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
returns ONLY the genuine ancestor messages, identified by
``session_id != tip_session_id``. (#65919)
"""
- if self._is_explicit_branch_session(session_id):
- return []
-
- session_ids = self._session_lineage_root_to_tip(session_id)
+ session_ids = self._resume_lineage_ids(session_id)
if len(session_ids) <= 1:
return []
with self._read_ctx() as conn:
diff --git a/tests/cli/test_resume_display.py b/tests/cli/test_resume_display.py
index 3c8755c31b8..e1c8fb2e5b7 100644
--- a/tests/cli/test_resume_display.py
+++ b/tests/cli/test_resume_display.py
@@ -323,6 +323,27 @@ class TestPreloadResumedSession:
assert "safe resume limit is 20000" in output.getvalue()
mock_db.get_resume_conversations.assert_not_called()
+ def test_tip_only_guard_goes_through_the_shared_resume_guard(self):
+ """The mid-setup path loads only the tip, so it asks the ONE resume
+ guard for a tip-only bound instead of borrowing the export guard."""
+ from hermes_state import SessionResumeTooLargeError
+
+ cli = _make_cli(resume="deep-lineage")
+ cli.session_id = "deep-lineage"
+ mock_db = MagicMock()
+ guard = MagicMock(return_value=666)
+ mock_db.assert_resume_safe = guard
+ cli._session_db = mock_db
+
+ assert cli._resume_history_limit_error(tip_only=True) is None
+ guard.assert_called_once_with("deep-lineage", tip_only=True)
+
+ guard.side_effect = SessionResumeTooLargeError(
+ 20_001, 20_000, scope="in its tip segment"
+ )
+ error = cli._resume_history_limit_error(tip_only=True)
+ assert error and "in its tip segment" in error
+
# ── Tests for _handle_resume_command recap display ───────────────────
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 54994c8b7b8..e3b09c97de0 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -4651,6 +4651,66 @@ class TestGetMessagesPagination:
assert exc_info.value.message_count == 5
assert exc_info.value.limit == 4
+ def test_resume_safety_tip_only_counts_the_tip_segment(self, db):
+ """A deep compression lineage behind a small tip resumes tip-only.
+
+ The Desktop Bot Chat shape: many compaction segments (~29k rows of
+ lineage) and a small live tip. Callers that never materialize the
+ ancestors (deferred / omit_messages / lazy resume, tip-only model
+ restore) must be bounded by the tip alone, and the message must name
+ the scope it counted.
+ """
+ prev = None
+ for i in range(6):
+ sid = f"seg-{i}"
+ kwargs = {"parent_session_id": prev} if prev else {}
+ db.create_session(session_id=sid, source="tui", **kwargs)
+ db.append_messages_batch(
+ sid,
+ [{"role": "user", "content": f"{sid}-{j}"} for j in range(4)],
+ )
+ if i < 5:
+ db.end_session(sid, "compression")
+ prev = sid
+
+ assert db.get_resume_message_count("seg-5") == 24
+ assert db.get_resume_message_count("seg-5", tip_only=True) == 4
+ with pytest.raises(hermes_state.SessionResumeTooLargeError) as full:
+ db.assert_resume_safe("seg-5", max_messages=10)
+ assert "across its lineage" in str(full.value)
+ assert db.assert_resume_safe("seg-5", max_messages=10, tip_only=True) == 4
+ with pytest.raises(hermes_state.SessionResumeTooLargeError) as tip:
+ db.assert_resume_safe("seg-5", max_messages=3, tip_only=True)
+ assert tip.value.message_count == 4
+ assert "in its tip segment" in str(tip.value)
+
+ def test_resume_guard_counts_exactly_what_a_branch_resume_loads(self, db):
+ """An explicit /branch copy owns its transcript: the guard and the
+ resume readers must agree that its lineage is itself alone."""
+ db.create_session(session_id="parent", source="tui")
+ db.append_messages_batch(
+ "parent",
+ [{"role": "user", "content": f"parent-{i}"} for i in range(6)],
+ )
+ db.create_session(
+ session_id="branch",
+ source="tui",
+ parent_session_id="parent",
+ model_config={"_branched_from": "parent"},
+ )
+ db.append_messages_batch(
+ "branch",
+ [{"role": "user", "content": f"branch-{i}"} for i in range(2)],
+ )
+
+ _, display = db.get_resume_conversations("branch")
+ assert len(display) == 2
+ assert db.get_ancestor_display_prefix("branch") == []
+ # Before: the guard walked parent_session_id and counted 8, so a branch
+ # could be refused for rows a resume would never load.
+ assert db.get_resume_message_count("branch") == 2
+ assert db.assert_resume_safe("branch", max_messages=5) == 2
+
def test_export_safety_is_bounded_to_the_requested_active_segment(self, db):
db.create_session(session_id="root", source="cli")
db.append_messages_batch(
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 774f70437d2..5412f333a88 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -806,6 +806,122 @@ def test_session_resume_rejects_runaway_transcript_before_history_load(
assert "safe resume limit is 20000" in response["error"]["message"]
+def test_session_resume_deferred_and_omitted_paths_guard_the_tip_only(server, monkeypatch):
+ """A deep compression lineage behind a small tip must open on Desktop.
+
+ Desktop's cold resume sends ``defer_history`` + ``omit_messages`` and pages
+ the transcript over REST, so the process only ever holds the tip segment.
+ Counting the whole lineage there returned 4130 for the healthiest sessions
+ (85 compaction segments / ~29k rows / ~700-row tip: Bot Chat stuck on
+ "Waking up…"). The guard must count what each path loads.
+ """
+ calls = []
+
+ class _DB:
+ def get_session(self, sid):
+ return {"id": sid, "message_count": 28_730}
+
+ def get_session_by_title(self, _title):
+ return None
+
+ def resolve_resume_session_id(self, sid):
+ return sid
+
+ def assert_resume_safe(self, sid, max_messages=None, *, tip_only=False):
+ calls.append(tip_only)
+ if not tip_only:
+ from hermes_state import SessionResumeTooLargeError
+
+ raise SessionResumeTooLargeError(20_001, 20_000)
+ return 666
+
+ def reopen_session(self, _sid):
+ raise RuntimeError("stop before history load")
+
+ monkeypatch.setattr(server, "_get_db", lambda: _DB())
+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
+
+ for params in (
+ {"defer_history": True, "omit_messages": True, "source": "desktop"},
+ {"omit_messages": True},
+ {"lazy": True},
+ ):
+ calls.clear()
+ response = server.handle_request(
+ {
+ "id": "r-tip",
+ "method": "session.resume",
+ "params": {"session_id": "deep-lineage", **params},
+ }
+ )
+ err = response.get("error") or {}
+ assert err.get("code") != 4130, params
+ assert calls == [True], params
+
+ # The non-deferred, non-omitted resume materializes the full lineage in
+ # memory, so it keeps the lineage-wide bound.
+ calls.clear()
+ response = server.handle_request(
+ {"id": "r-full", "method": "session.resume", "params": {"session_id": "deep-lineage"}}
+ )
+ assert response["error"]["code"] == 4130
+ assert calls == [False]
+
+
+def test_deferred_hydration_falls_back_to_tip_when_lineage_exceeds_limit(server, monkeypatch):
+ """The hydration worker never loads a lineage the guard would refuse."""
+ import threading
+
+ from hermes_state import SessionResumeTooLargeError
+
+ tip = [{"role": "user", "content": "tip"}]
+ reads = []
+
+ class _DB:
+ def reopen_session(self, _sid):
+ return True
+
+ def assert_resume_safe(self, sid, max_messages=None, *, tip_only=False):
+ if not tip_only:
+ raise SessionResumeTooLargeError(20_001, 20_000)
+ return 1
+
+ def get_resume_conversations(self, _sid):
+ reads.append("lineage")
+ raise AssertionError("must not materialize the runaway lineage")
+
+ def get_ancestor_display_prefix(self, _sid):
+ reads.append("prefix")
+ raise AssertionError("must not materialize the runaway lineage")
+
+ def get_messages_as_conversation(self, sid, **kwargs):
+ reads.append(("tip", kwargs.get("repair_alternation")))
+ return list(tip)
+
+ built = threading.Event()
+ monkeypatch.setattr(server, "_start_agent_build", lambda _sid, _session: built.set())
+ monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *_a, **_k: None)
+
+ session = server._deferred_session_record(
+ "deep-lineage", cols=80, cwd="/tmp", history=[], lease=None
+ )
+ session["resume_history_ready"] = threading.Event()
+ session["resume_hydrating"] = True
+ session["resume_message_count"] = 28_730
+ server._sessions["hyd"] = session
+ try:
+ server._schedule_resume_hydration("hyd", "deep-lineage", _DB())
+ assert session["resume_history_ready"].wait(timeout=5)
+ assert built.wait(timeout=5)
+ assert session.get("resume_history_error") is None
+ assert session["history"] == tip
+ assert session["display_history_prefix"] == []
+ assert session["resume_message_count"] == 1
+ assert reads == [("tip", True)]
+ finally:
+ server._sessions.pop("hyd", None)
+
+
def test_session_resume_guard_failure_fails_open(server, monkeypatch):
"""A transient guard error must not block resume (fail open, log only)."""
reopened = []
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 8a5afd05487..dcceee5c7ac 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -659,20 +659,37 @@ def _(rid, params: dict) -> dict:
# (see _todo_state_from_history) — no extra transcript read here.
# Every interactive resume path materializes the model history, even when
- # omit_messages suppresses the response copy. Count the complete lineage
- # before any reopen/history read so a runaway transcript cannot exhaust
- # the dashboard. The metadata fallback keeps lightweight test/adaptor DBs
- # that predate the shared SessionDB guard compatible. The limit resolves
- # from config (sessions.max_resume_messages, 0 disables).
+ # omit_messages suppresses the response copy. Count what THIS path will
+ # actually load before any reopen/history read so a runaway transcript
+ # cannot exhaust the dashboard. Only the non-deferred, non-omitted
+ # resume reads the whole compression lineage (ancestors → tip) into
+ # memory; the deferred Desktop resume (display transcript paged over
+ # REST), the omit_messages resume, and the lazy watch resume all load
+ # the TIP segment only — guarding those against the full-lineage count
+ # rejected exactly the well-compressed conversations compaction is
+ # meant to produce (85 segments / ~29k lineage rows / ~700-row tip →
+ # 4130 and a Bot Chat stuck on "Waking up…"). The metadata fallback
+ # keeps lightweight test/adaptor DBs that predate the shared SessionDB
+ # guard compatible. The limit resolves from config
+ # (sessions.max_resume_messages, 0 disables).
from hermes_state import (
SessionResumeTooLargeError,
resolved_max_resume_messages,
)
+ eager_build = is_truthy_value(params.get("eager_build", False))
+ guard_tip_only = (
+ is_truthy_value(params.get("lazy", False))
+ or omit_messages
+ or (defer_history and not eager_build)
+ )
safety_check = getattr(db, "assert_resume_safe", None)
try:
if callable(safety_check):
- safety_check(target)
+ if guard_tip_only:
+ safety_check(target, tip_only=True)
+ else:
+ safety_check(target)
else:
resume_limit = resolved_max_resume_messages()
stored_message_count = int(found.get("message_count") or 0)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index fa8694a13d4..ab5dcfe9b5e 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -10851,8 +10851,39 @@ def _schedule_resume_hydration(
{"phase": "history", "status": "loading"},
)
db.reopen_session(stored_id)
- raw_history, display_history = db.get_resume_conversations(stored_id)
- prefix = db.get_ancestor_display_prefix(stored_id)
+ from hermes_state import SessionResumeTooLargeError
+
+ # The deferred resume is guarded tip-only (session.resume): the
+ # display transcript is REST-paginated, so the ancestor prefix is
+ # an in-memory convenience (rewind ordinal translation, branch
+ # snapshots), not a requirement. Materialize the full lineage only
+ # while it fits sessions.max_resume_messages; past that, hydrate
+ # the tip alone instead of loading the runaway lineage the guard
+ # exists to keep out of memory (the omit_messages resume already
+ # runs with an empty prefix, so this is an existing shape).
+ prefix_fits = True
+ guard = getattr(db, "assert_resume_safe", None)
+ if callable(guard):
+ try:
+ guard(stored_id)
+ except SessionResumeTooLargeError as exc:
+ prefix_fits = False
+ logger.info(
+ "resume %s: compression lineage exceeds the resume "
+ "limit (%s); hydrating the tip segment only",
+ stored_id, exc,
+ )
+ except Exception:
+ logger.debug("resume lineage guard failed; loading full lineage", exc_info=True)
+ if prefix_fits:
+ raw_history, display_history = db.get_resume_conversations(stored_id)
+ prefix = db.get_ancestor_display_prefix(stored_id)
+ else:
+ raw_history = db.get_messages_as_conversation(
+ stored_id, repair_alternation=True, include_row_ids=True
+ )
+ display_history = raw_history
+ prefix = []
history = sanitize_replay_history(raw_history)
if _sessions.get(sid) is not session:
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index af18e5c5ba4..7662aaa9da5 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -888,6 +888,34 @@ Active sessions are never auto-pruned, regardless of age. Ended sessions are
aged from their latest message, so a long-lived conversation used recently is
not deleted merely because it began before the retention window.
+### Oversized-Transcript Guards
+
+Two limits stop a runaway transcript from being loaded into memory all at once
+(both default to `20000` active messages; `0` disables the guard):
+
+```yaml
+sessions:
+ max_resume_messages: 20000 # interactive resume (CLI / TUI / Desktop)
+ max_export_messages: 20000 # one-shot in-memory export of a single session
+```
+
+`max_resume_messages` bounds **what the resume actually loads**, not the whole
+history of the conversation:
+
+- A plain interactive resume (CLI `--resume`, the TUI) materializes the full
+ compression lineage — every compacted segment plus the live tip — so it is
+ bounded across the lineage.
+- Desktop's cold resume pages the transcript over REST and only holds the live
+ tip segment in memory, so it is bounded by the tip alone. A long-lived chat
+ that has been compacted many times (dozens of segments, tens of thousands of
+ archived rows behind a small tip) is exactly what compression is meant to
+ produce and opens normally; its footer message count reflects the stored
+ lineage, not the live prompt.
+
+When a resume is refused the client receives error code `4130` with the count
+and the scope it was measured against (`across its lineage` or
+`in its tip segment`). `hermes sessions export` still works for such sessions.
+
### Manual Cleanup
```bash