The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve pending transcript state on failed rewinds
poisdahl67ee48162144
diff --git a/gateway/session.py b/gateway/session.pyindex 123deaf0f0f..efb70d7d4af 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -3480,17 +3480,21 @@ class SessionStore:entry = self._entries.get(session_key)return getattr(entry, "session_id", None) if entry else None- def append_to_transcript(self, session_id: str, message: Dict[str, Any], skip_db: bool = False) -> None:- """Serialize transcript draining across queue migration boundaries."""- if not self._db or skip_db:- return+ def _get_transcript_drain_lock(self):+ """Return the lock that serializes pending-queue drain boundaries."""drain_lock = getattr(self, "_transcript_drain_lock", None)if drain_lock is None:# Compatibility for old in-memory/test instances created via# object.__new__ before this field existed.drain_lock = threading.RLock()self._transcript_drain_lock = drain_lock- with drain_lock:+ return drain_lock++ def append_to_transcript(self, session_id: str, message: Dict[str, Any], skip_db: bool = False) -> None:+ """Serialize transcript draining across queue migration boundaries."""+ if not self._db or skip_db:+ return+ with self._get_transcript_drain_lock():reroutes = getattr(self, "_transcript_reroutes", None)if reroutes is None:reroutes = {}@@ -3844,18 +3848,19 @@ class SessionStore:"""if not self._db:return True- self._clear_dirty_transcript(session_id)- try:- self._db.replace_messages(- session_id,- messages,- active_only=active_only,- reject_active_turn_lease=reject_active_turn_lease,- )+ with self._get_transcript_drain_lock():+ try:+ self._db.replace_messages(+ session_id,+ messages,+ active_only=active_only,+ reject_active_turn_lease=reject_active_turn_lease,+ )+ except Exception as e:+ logger.debug("Failed to rewrite transcript in DB: %s", e)+ return False+ self._clear_dirty_transcript(session_id)return True- except Exception as e:- logger.debug("Failed to rewrite transcript in DB: %s", e)- return Falsedef load_transcript(self, session_id: str) -> List[Dict[str, Any]]:"""Load all messages from a session's transcript.@@ -3930,82 +3935,83 @@ class SessionStore:"""if not self._db:return None- self._clear_dirty_transcript(session_id)- if n < 1:- n = 1- from agent.context_compressor import (- retryable_user_text,- split_user_originated_turn,- user_originated_turn_view,- )-- try:- durable = self._db.get_messages_as_conversation(- session_id,- include_row_ids=True,+ with self._get_transcript_drain_lock():+ if n < 1:+ n = 1+ from agent.context_compressor import (+ retryable_user_text,+ split_user_originated_turn,+ user_originated_turn_view,)- expected_active_ids = [- int(message["_row_id"])- for message in durable- if isinstance(message.get("_row_id"), int)- ]- user_indices = [- index- for index, message in enumerate(durable)- if user_originated_turn_view(message) is not None- ]- if not user_indices:++ try:+ durable = self._db.get_messages_as_conversation(+ session_id,+ include_row_ids=True,+ )+ expected_active_ids = [+ int(message["_row_id"])+ for message in durable+ if isinstance(message.get("_row_id"), int)+ ]+ user_indices = [+ index+ for index, message in enumerate(durable)+ if user_originated_turn_view(message) is not None+ ]+ if not user_indices:+ return None+ turns_undone = min(n, len(user_indices))+ target = durable[user_indices[-turns_undone]]+ target_id = target.get("_row_id")+ if not isinstance(target_id, int):+ return None+ handoff, target_view = split_user_originated_turn(target)+ if target_view is None:+ return None+ if require_retryable_composite:+ if handoff is None:+ return None+ target_text = retryable_user_text(target_view.get("content"))+ except Exception as e:+ logger.debug("rewind_session: failed to resolve canonical target: %s", e)return None- turns_undone = min(n, len(user_indices))- target = durable[user_indices[-turns_undone]]- target_id = target.get("_row_id")- if not isinstance(target_id, int):+ try:+ result = self._db.rewind_to_message(+ session_id,+ target_id,+ preserve_compaction_handoff=handoff is not None,+ expected_active_ids=expected_active_ids,+ expected_target_content=target_view.get("content"),+ )+ except ValueError as e:+ logger.debug("rewind_session: %s", e)return None- handoff, target_view = split_user_originated_turn(target)- if target_view is None:+ except Exception as e:+ logger.debug("rewind_session: rewind_to_message failed: %s", e)return None- if require_retryable_composite:- if handoff is None:- return None- target_text = retryable_user_text(target_view.get("content"))- except Exception as e:- logger.debug("rewind_session: failed to resolve canonical target: %s", e)- return None- try:- result = self._db.rewind_to_message(- session_id,- target_id,- preserve_compaction_handoff=handoff is not None,- expected_active_ids=expected_active_ids,- expected_target_content=target_view.get("content"),- )- except ValueError as e:- logger.debug("rewind_session: %s", e)- return None- except Exception as e:- logger.debug("rewind_session: rewind_to_message failed: %s", e)- return None- # ``target_view`` is the canonical live projection of the physical DB- # row. For a composite carrier, the raw target contains the historical- # summary wrapper and must never be echoed back as the editable prompt.- if not require_retryable_composite:- content = target_view.get("content") or ""- if isinstance(content, list):- parts = [- p.get("text", "")- for p in content- if isinstance(p, dict) and p.get("type") == "text"- ]- target_text = "\n".join(t for t in parts if t)- elif isinstance(content, str):- target_text = content- else:- target_text = ""- return {- "rewound_count": result.get("rewound_count", 0),- "turns_undone": turns_undone,- "target_text": target_text,- }+ self._clear_dirty_transcript(session_id)+ # ``target_view`` is the canonical live projection of the physical DB+ # row. For a composite carrier, the raw target contains the historical+ # summary wrapper and must never be echoed back as the editable prompt.+ if not require_retryable_composite:+ content = target_view.get("content") or ""+ if isinstance(content, list):+ parts = [+ p.get("text", "")+ for p in content+ if isinstance(p, dict) and p.get("type") == "text"+ ]+ target_text = "\n".join(t for t in parts if t)+ elif isinstance(content, str):+ target_text = content+ else:+ target_text = ""+ return {+ "rewound_count": result.get("rewound_count", 0),+ "turns_undone": turns_undone,+ "target_text": target_text,+ }def build_session_context(diff --git a/tests/gateway/test_retry_replacement.py b/tests/gateway/test_retry_replacement.pyindex 35394cc688f..b3f2e8d96f0 100644--- a/tests/gateway/test_retry_replacement.py+++ b/tests/gateway/test_retry_replacement.py@@ -1,5 +1,7 @@"""Regression tests for /retry replacement and carrier-aware undo semantics."""+import os+import threadingfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -26,6 +28,173 @@ def _composite_carrier(ask="REAL ASK"):}+def _seed_pending_recovery(store, session_id):+ pending = {"role": "assistant", "content": "pending recovery answer"}+ store._dirty_transcripts[session_id] = [dict(pending)]+ store._transcript_append_failures[session_id] = 3+ return pending+++def test_rewrite_transcript_keeps_pending_recovery_state_when_lease_rejects(+ tmp_path, monkeypatch+):+ import hermes_state++ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())+ session_id = "rewrite-pending-lease"+ store._db.create_session(session_id=session_id, source="test")+ store._db.append_message(session_id, "user", "old ask")+ pending = _seed_pending_recovery(store, session_id)+ before = store._db.get_messages(session_id, include_inactive=True)+ holder = f"pid={os.getpid()}:turn=foreign"+ assert store._db.try_acquire_session_turn_lease(+ session_id, holder, ttl_seconds=60+ )++ assert not store.rewrite_transcript(+ session_id,+ [{"role": "user", "content": "replacement ask"}],+ active_only=True,+ reject_active_turn_lease=True,+ )++ assert store._db.get_messages(session_id, include_inactive=True) == before+ assert store._dirty_transcripts[session_id] == [pending]+ assert store._transcript_append_failures[session_id] == 3++ store._db.release_session_turn_lease(session_id, holder)+ assert store.rewrite_transcript(+ session_id,+ [{"role": "user", "content": "replacement ask"}],+ active_only=True,+ reject_active_turn_lease=True,+ )+ assert session_id not in store._dirty_transcripts+ assert session_id not in store._transcript_append_failures+++def test_rewind_session_keeps_pending_recovery_state_when_lease_rejects(+ tmp_path, monkeypatch+):+ import hermes_state++ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())+ session_id = "rewind-pending-lease"+ store._db.create_session(session_id=session_id, source="test")+ store._db.append_message(session_id, "user", _composite_carrier()["content"])+ store._db.append_message(session_id, "assistant", "old answer")+ pending = _seed_pending_recovery(store, session_id)+ before = store._db.get_messages(session_id, include_inactive=True)+ holder = f"pid={os.getpid()}:turn=foreign"+ assert store._db.try_acquire_session_turn_lease(+ session_id, holder, ttl_seconds=60+ )++ assert (+ store.rewind_session(session_id, require_retryable_composite=True) is None+ )++ assert store._db.get_messages(session_id, include_inactive=True) == before+ assert store._dirty_transcripts[session_id] == [pending]+ assert store._transcript_append_failures[session_id] == 3++ store._db.release_session_turn_lease(session_id, holder)+ result = store.rewind_session(+ session_id, require_retryable_composite=True+ )+ assert result is not None+ assert result["target_text"] == "REAL ASK"+ assert session_id not in store._dirty_transcripts+ assert session_id not in store._transcript_append_failures++[email protected]("operation", ["rewrite", "rewind"])+def test_transcript_mutation_serializes_pending_queue_drain(+ operation, tmp_path, monkeypatch+):+ import hermes_state++ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", tmp_path / "state.db")+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())+ session_id = f"serialized-{operation}"+ store._db.create_session(session_id=session_id, source="test")+ store._db.append_message(session_id, "user", _composite_carrier()["content"])+ store._db.append_message(session_id, "assistant", "old answer")+ _seed_pending_recovery(store, session_id)++ mutation_entered = threading.Event()+ release_mutation = threading.Event()+ append_started = threading.Event()+ append_done = threading.Event()+ errors = []++ if operation == "rewrite":+ original_mutation = store._db.replace_messages++ def gated_mutation(*args, **kwargs):+ mutation_entered.set()+ assert release_mutation.wait(timeout=5)+ return original_mutation(*args, **kwargs)++ monkeypatch.setattr(store._db, "replace_messages", gated_mutation)++ def mutate():+ assert store.rewrite_transcript(+ session_id,+ [{"role": "user", "content": "replacement ask"}],+ active_only=True,+ )++ else:+ original_mutation = store._db.rewind_to_message++ def gated_mutation(*args, **kwargs):+ mutation_entered.set()+ assert release_mutation.wait(timeout=5)+ return original_mutation(*args, **kwargs)++ monkeypatch.setattr(store._db, "rewind_to_message", gated_mutation)++ def mutate():+ assert store.rewind_session(session_id) is not None++ def run_mutation():+ try:+ mutate()+ except BaseException as exc: # surface worker failures in the test thread+ errors.append(exc)++ def append_after_mutation_starts():+ append_started.set()+ try:+ store.append_to_transcript(+ session_id,+ {"role": "assistant", "content": "concurrent answer"},+ )+ except BaseException as exc: # surface worker failures in the test thread+ errors.append(exc)+ finally:+ append_done.set()++ mutation_thread = threading.Thread(target=run_mutation)+ mutation_thread.start()+ assert mutation_entered.wait(timeout=5)+ append_thread = threading.Thread(target=append_after_mutation_starts)+ append_thread.start()+ assert append_started.wait(timeout=5)+ assert not append_done.wait(timeout=0.1)++ release_mutation.set()+ mutation_thread.join(timeout=5)+ append_thread.join(timeout=5)+ assert not mutation_thread.is_alive()+ assert not append_thread.is_alive()+ assert errors == []+ assert store.load_transcript(session_id)[-1]["content"] == "concurrent answer"++@pytest.mark.asyncioasync def test_gateway_retry_replaces_last_user_turn_in_transcript(tmp_path, monkeypatch):# Pin DEFAULT_DB_PATH so SessionDB() doesn't write to the real ~/.hermes/state.db.