Skip to content

The agent that grows with you

fix(gateway): stop false "failed to persist compressed transcript" on rotated /compress

Ned6cde26856f21
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 60ca6400f05..b9810e02567 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1121,7 +1121,18 @@ class GatewayTurnMixin:
# conversation silently vanishes. Persist the child transcript first; only then rebind the live
# entry.
if _hyg_rotated:
- if not await self.async_session_store.rewrite_transcript(_hyg_new_sid, _compressed):
+ # Same false-failure guard as manual /compress: publish_compression_child() wrote the
+ # handoff + cloned foreign tail atomically, so the durable child needs no second
+ # rewrite. rewrite_transcript() here DELETEs those cloned rows (they are absent from
+ # _compressed) and any DB hiccup used to fail the whole rotation fail-closed onto the
+ # already-superseded parent. Probe fails open: False keeps the original rewrite path.
+ if await self.async_session_store.is_published_compression_child(
+ session_entry.session_id, _hyg_new_sid):
+ _hyg_new_sid_persisted = True
+ else:
+ _hyg_new_sid_persisted = await self.async_session_store.rewrite_transcript(
+ _hyg_new_sid, _compressed)
+ if not _hyg_new_sid_persisted:
logger.error(
"Session hygiene: failed to persist compressed transcript for rotated session "
"%s → %s; keeping the live entry on the original session so the "
diff --git a/gateway/session_transcript.py b/gateway/session_transcript.py
index ccc1e76b94b..1e2ca0ce5c7 100644
--- a/gateway/session_transcript.py
+++ b/gateway/session_transcript.py
@@ -513,6 +513,33 @@ class SessionTranscriptMixin:
self._clear_dirty_transcript(session_id)
return True
+ def is_published_compression_child(self, parent_session_id: str, child_session_id: str) -> bool:
+ """True when *child_session_id* is an atomically-published compression continuation of
+ *parent_session_id*: ``publish_compression_child()`` wrote the handoff (plus any cloned
+ foreign-tail rows) in the SAME transaction that ended the parent with
+ ``end_reason='compression'``, so the child transcript is already durable on disk.
+
+ /compress and hygiene rewrite the rotated child AGAIN; when this returns True that second
+ rewrite is redundant AND destructive (the in-memory handoff list lacks the rows cloned
+ during publication) and its failure surfaces as a false "failed to persist compressed
+ transcript" over an already-committed compression. Fails open (False) on any DB error so
+ callers fall back to the rewrite guard exactly as before."""
+ if not parent_session_id or not child_session_id:
+ return False
+ db = self._db_for_session_id(child_session_id)
+ if db is None:
+ return False
+ try:
+ child = db.get_session(child_session_id)
+ if not child or child.get("parent_session_id") != parent_session_id:
+ return False
+ if not db._is_compression_child_row(child):
+ return False
+ return db.get_active_message_watermark(child_session_id) > 0
+ except Exception:
+ logger.debug("published-compression-child probe failed for %s", child_session_id, exc_info=True)
+ return False
+
def has_input_owner(self, session_id: str, owner: str) -> bool:
"""Find this accepted input on the canonical live continuation and its ancestors.
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 4f07bbcd430..15921d42ff5 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -627,9 +627,17 @@ class GatewaySessionCommandsMixin:
archive; an unchanged id without in-place means rotation FAILED."""
new_session_id = tmp_agent.session_id
if new_session_id != session_entry.session_id:
- if not await self.async_session_store.rewrite_transcript(new_session_id, compressed):
- raise RuntimeError(
- f"failed to persist compressed transcript for session {new_session_id}")
+ # Rotation path: _publish_rotated_compaction() already wrote the compressed handoff
+ # (plus any foreign-tail rows cloned during the same transaction) into the NEW session
+ # durably. A second rewrite is redundant and destructive — `compressed` lacks those
+ # cloned rows — and its failure used to surface as a false "failed to persist
+ # compressed transcript" even though the compression had committed. Skip the rewrite
+ # when the durable child is verified; fail-open keeps the original guard.
+ if not await self.async_session_store.is_published_compression_child(
+ session_entry.session_id, new_session_id):
+ if not await self.async_session_store.rewrite_transcript(new_session_id, compressed):
+ raise RuntimeError(
+ f"failed to persist compressed transcript for session {new_session_id}")
session_entry.session_id = new_session_id
await self.async_session_store._save()
await asyncio.to_thread(self._sync_telegram_topic_binding, source, session_entry,
diff --git a/tests/gateway/test_compress_command.py b/tests/gateway/test_compress_command.py
index 8502a8c3a74..564f5acd2d3 100644
--- a/tests/gateway/test_compress_command.py
+++ b/tests/gateway/test_compress_command.py
@@ -3,6 +3,7 @@
import asyncio
import threading
from datetime import datetime
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -517,3 +518,101 @@ async def test_compress_command_cleanup_does_not_block_event_loop():
"event loop was blocked during manual /compress cleanup: only "
f"{observed.get('ticks_during_block')} ticks while agent.close() was running"
)
+
+
[email protected]("profile", ["main", "sean"])
+def test_rotated_compress_keeps_atomically_published_foreign_tail(tmp_path, profile, monkeypatch):
+ """A rotated /compress must NOT rewrite the atomically-published child.
+
+ publish_compression_child() writes handoff + cloned foreign tail in one transaction;
+ the second rewrite_transcript(active_only=False) would DELETE the cloned tail (it is not
+ in the in-memory handoff) and its failure surfaced as a false "failed to persist
+ compressed transcript" even though the compression had already committed.
+ """
+ import hermes_state
+ from gateway.slash_commands_session import GatewaySessionCommandsMixin
+ from gateway.session import AsyncSessionStore, SessionStore
+ from gateway.config import GatewayConfig
+
+ db_path = tmp_path / profile / "state.db"
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", db_path)
+ store = SessionStore(sessions_dir=tmp_path / profile, config=GatewayConfig())
+ db = store._db
+ parent, child = "parent", "child"
+ db.create_session(parent, "discord")
+ db.append_message(parent, "assistant", "old turn")
+ watermark = db.get_active_message_watermark(parent)
+ db.append_message(parent, "assistant", "concurrent foreign turn")
+ ceiling = db.get_active_message_watermark(parent)
+ handoff = [{"role": "assistant", "content": "compressed summary"}]
+ db.publish_compression_child(
+ parent_session_id=parent, child_session_id=child, source="discord",
+ messages=handoff, watermark=watermark, watermark_ceiling=ceiling,
+ require_compression_lease=False,
+ )
+
+ def _destructive_rewrite(*_args, **_kwargs):
+ raise AssertionError("published child must not be rewritten")
+ store.rewrite_transcript = _destructive_rewrite
+
+ entry = SessionEntry(
+ session_key=f"agent:{profile}:discord:thread:123:123", session_id=parent,
+ created_at=datetime.now(), updated_at=datetime.now(),
+ platform=Platform.DISCORD, chat_type="thread",
+ )
+ runner = SimpleNamespace(
+ async_session_store=AsyncSessionStore(store),
+ _sync_telegram_topic_binding=MagicMock(),
+ )
+ agent = SimpleNamespace(session_id=child)
+ try:
+ asyncio.run(GatewaySessionCommandsMixin._persist_manual_compression(
+ runner, agent, entry, _make_source(), handoff))
+ assert entry.session_id == child
+ assert [m["content"] for m in db.get_messages(child)] == [
+ "compressed summary", "concurrent foreign turn",
+ ]
+ finally:
+ store.close_all_db_handles()
+
+
+def test_compress_falls_back_to_rewrite_for_unpublished_child(tmp_path, monkeypatch):
+ """Fail-open contract: when the child is NOT a durably-published compression continuation
+ (probe False), the original rewrite-then-repoint guard must still run unchanged."""
+ import hermes_state
+ from gateway.slash_commands_session import GatewaySessionCommandsMixin
+ from gateway.session import AsyncSessionStore, SessionStore
+ from gateway.config import GatewayConfig
+
+ db_path = tmp_path / "state.db"
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", db_path)
+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
+ db = store._db
+ parent, child = "parent2", "child2"
+ db.create_session(parent, "discord")
+ db.create_session(child, "discord") # no compression lineage at all
+ entry = SessionEntry(
+ session_key="agent:fallback:discord:thread:9:9", session_id=parent,
+ created_at=datetime.now(), updated_at=datetime.now(),
+ platform=Platform.DISCORD, chat_type="thread",
+ )
+ rewrite_calls = []
+
+ def _fake_rewrite(session_id, messages, **kwargs):
+ rewrite_calls.append((session_id, messages))
+ return True
+ store.rewrite_transcript = _fake_rewrite
+
+ runner = SimpleNamespace(
+ async_session_store=AsyncSessionStore(store),
+ _sync_telegram_topic_binding=MagicMock(),
+ )
+ agent = SimpleNamespace(session_id=child)
+ compressed = [{"role": "assistant", "content": "summary"}]
+ try:
+ asyncio.run(GatewaySessionCommandsMixin._persist_manual_compression(
+ runner, agent, entry, _make_source(), compressed))
+ assert entry.session_id == child
+ assert rewrite_calls == [(child, compressed)]
+ finally:
+ store.close_all_db_handles()