Skip to content

The agent that grows with you

fix(gateway): preserve archived compaction history on /retry

Adolanium56fbac6b3858
diff --git a/gateway/session.py b/gateway/session.py
index 53116372c1c..83dad95befa 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -3362,11 +3362,41 @@ class SessionStore:
logger.debug("has_platform_message_id lookup failed", exc_info=True)
return False
- def rewrite_transcript(self, session_id: str, messages: List[Dict[str, Any]]) -> bool:
+ def has_archived_messages(self, session_id: str) -> bool:
+ """Check if a session has any soft-archived (``active = 0``) rows.
+
+ Thin wrapper over SessionDB.has_archived_messages(). Returns False
+ when no DB is available (in-memory sessions). Used by transcript
+ rewrite callers (e.g. /retry) to decide whether the rewrite must
+ pass ``active_only=True`` so archived compaction history survives.
+ """
+ if not self._db:
+ return False
+ try:
+ return self._db.has_archived_messages(session_id)
+ except Exception:
+ logger.debug("has_archived_messages lookup failed", exc_info=True)
+ return False
+
+ def rewrite_transcript(
+ self,
+ session_id: str,
+ messages: List[Dict[str, Any]],
+ active_only: bool = False,
+ ) -> bool:
"""Replace the entire transcript for a session with new messages.
- Used by /retry, /undo, and /compress to persist modified conversation
- history. state.db is the canonical store.
+ Used by /retry and /compress to persist modified conversation
+ history. state.db is the canonical store. (/undo is not a caller:
+ it soft-archives rows via rewind_session / rewind_to_message.)
+
+ DESTRUCTIVE by default: ``replace_messages(active_only=False)``
+ DELETEs every row for the session, including the soft-archived
+ compaction history that archive_and_compact() keeps on disk
+ (#38763). Callers rewriting the live transcript of a session that
+ may carry archived rows must pass ``active_only=True`` so only the
+ live rows are replaced; callers that mean to purge (e.g. yuanbao
+ recall redaction) keep the default.
Returns ``True`` when the write lands (or there is no DB to write to)
and ``False`` when the canonical write fails. Most callers can ignore
@@ -3379,7 +3409,7 @@ class SessionStore:
return True
self._clear_dirty_transcript(session_id)
try:
- self._db.replace_messages(session_id, messages)
+ self._db.replace_messages(session_id, messages, active_only=active_only)
return True
except Exception as e:
logger.debug("Failed to rewrite transcript in DB: %s", e)
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index c65acc814f5..5305afc6508 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -2582,9 +2582,19 @@ class GatewaySlashCommandsMixin:
if not last_user_msg:
return t("gateway.retry.no_previous")
- # Truncate history to before the last user message and persist
+ # Truncate history to before the last user message and persist. Probe
+ # for soft-archived rows first: after an in-place compaction the
+ # pre-compaction transcript lives on as active=0/compacted=1 rows
+ # under this same session id, and a bare rewrite (active_only=False)
+ # would DELETE them (same class as #61145; ACP _persist and TUI
+ # prompt.submit already guard their rewrite paths).
truncated = history[:last_user_idx]
- await self.async_session_store.rewrite_transcript(session_entry.session_id, truncated)
+ has_archived = await self.async_session_store.has_archived_messages(
+ session_entry.session_id
+ )
+ await self.async_session_store.rewrite_transcript(
+ session_entry.session_id, truncated, active_only=has_archived
+ )
# Reset stored token count — transcript was truncated
session_entry.last_prompt_tokens = 0
diff --git a/tests/gateway/test_retry_replacement.py b/tests/gateway/test_retry_replacement.py
index bdc7a78d05f..da219a7ef56 100644
--- a/tests/gateway/test_retry_replacement.py
+++ b/tests/gateway/test_retry_replacement.py
@@ -67,3 +67,79 @@ async def test_gateway_retry_replaces_last_user_turn_in_transcript(tmp_path, mon
]
+async def test_gateway_retry_preserves_archived_compaction_rows(tmp_path, monkeypatch):
+ """/retry must not DELETE soft-archived compaction history.
+
+ With compression.in_place (the default, #38763) archive_and_compact()
+ keeps the pre-compaction transcript on disk as active=0/compacted=1 rows
+ under the same session id. /retry used to persist its truncation via a
+ bare rewrite_transcript(), whose replace_messages(active_only=False)
+ DELETEs every row for the session and reinserts only the truncated live
+ tail, wiping the archived history permanently (same class as #61145;
+ #57803 named this call site as a residual gap). The handler must probe
+ has_archived_messages() and pass active_only=True so only the live rows
+ are replaced.
+ """
+ import hermes_state
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")
+
+ config = GatewayConfig()
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+
+ session_id = "retry_archived_session"
+ store._db.create_session(session_id=session_id, source="test")
+ store._db.append_message(session_id=session_id, role="user", content="old question")
+ store._db.append_message(session_id=session_id, role="assistant", content="old answer")
+ # In-place compaction: the two rows above are soft-archived and the
+ # compacted transcript becomes the live set under the same id.
+ store._db.archive_and_compact(
+ session_id,
+ [
+ {"role": "user", "content": "first question"},
+ {"role": "assistant", "content": "first answer"},
+ {"role": "user", "content": "retry me"},
+ {"role": "assistant", "content": "old answer"},
+ ],
+ )
+ assert store._db.has_archived_messages(session_id) is True
+
+ gw = GatewayRunner.__new__(GatewayRunner)
+ gw.config = config
+ gw.session_store = store
+
+ session_entry = MagicMock(session_id=session_id)
+ session_entry.last_prompt_tokens = 111
+ gw.session_store.get_or_create_session = MagicMock(return_value=session_entry)
+
+ async def fake_handle_message(event):
+ assert event.text == "retry me"
+ store.append_to_transcript(session_id, {"role": "user", "content": event.text})
+ store.append_to_transcript(session_id, {"role": "assistant", "content": "new answer"})
+ return "new answer"
+
+ gw._handle_message = AsyncMock(side_effect=fake_handle_message)
+
+ result = await gw._handle_retry_command(
+ MessageEvent(text="/retry", message_type=MessageType.TEXT, source=MagicMock())
+ )
+
+ assert result == "new answer"
+ # The archived pre-compaction rows survive the rewrite untouched.
+ archived = [
+ m for m in store._db.get_messages(session_id, include_inactive=True)
+ if not m["active"]
+ ]
+ assert [(m["role"], m["content"]) for m in archived] == [
+ ("user", "old question"),
+ ("assistant", "old answer"),
+ ]
+ assert all(m["compacted"] == 1 for m in archived)
+ # The live set reflects the truncation plus the retried exchange.
+ transcript_after = store.load_transcript(session_id)
+ assert [m.get("content") for m in transcript_after if m.get("role") == "user"] == [
+ "first question",
+ "retry me",
+ ]
+
+