The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): reject stale manual snapshots after lease admission
funky-xamarin35c9242fcf03
diff --git a/agent/compression_facade.py b/agent/compression_facade.pyindex 6d6eed58d39..8b981b27da3 100644--- a/agent/compression_facade.py+++ b/agent/compression_facade.py@@ -222,7 +222,7 @@ class CompressionFacadeMixin:self, messages: list, system_message: str, *, approx_tokens: int = None, task_id: str = "default",focus_topic: str = None, force: bool = False, bypass_cooldown: bool = False,defer_context_engine_notification: bool = False, commit_fence=None, verbatim_tail: list = None,- trigger: str = None,+ trigger: str = None, snapshot_is_current=None,) -> tuple:"""Forwarder — see ``agent.conversation_compression.compress_context``.``force=True`` (manual /compress) bypasses the summary-failure cooldown; ``bypass_cooldown=True``@@ -283,6 +283,7 @@ class CompressionFacadeMixin:bypass_cooldown=bypass_cooldown or same_turn_fallback_recovery,defer_context_engine_notification=(defer_context_engine_notification), commit_fence=fence,verbatim_tail=verbatim_tail, trigger=trigger,+ **({"snapshot_is_current": snapshot_is_current} if snapshot_is_current is not None else {}),)# Callers that already own a progress-aware wait (gateway sessiondiff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex ec4727c61bf..8f09386a5f4 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -4074,7 +4074,7 @@ def compress_context(task_id: str = "default", focus_topic: Optional[str] = None, force: bool = False,bypass_cooldown: bool = False, defer_context_engine_notification: bool = False,commit_fence: Optional[CompressionCommitFence] = None, verbatim_tail: Optional[list] = None,- trigger: Optional[str] = None,+ trigger: Optional[str] = None, snapshot_is_current: Optional[Callable[[], bool]] = None,) -> Tuple[list, str]:"""Compress conversation context and split the session in SQLite.``force`` (manual /compress) clears the summary-failure cooldown; ``bypass_cooldown`` (provider-proven@@ -4099,6 +4099,8 @@ def compress_context(after ``messages``; an in-place commit stores them after the compacted head and returns head + tail.trigger: Why this attempt runs (``"overflow"`` for provider-rejected requests); defaults to manual/autofrom ``force``. Feeds attempt telemetry only.+ snapshot_is_current: Optional host snapshot validation after durable lease admission. This protects+ edits completed before admission; it is not a substitute for the host's final publication fence."""attempt = _begin_compression_attempt(agent, force=force, defer_notification=defer_context_engine_notification, trigger=trigger,@@ -4155,6 +4157,13 @@ def compress_context(# Publish the holder-qualified release hook before a timeout can win the# fence. If no durable lock was acquired there is no hook to publish.lease.finish_lock_setup()+ try:+ if snapshot_is_current is not None and not snapshot_is_current():+ lease.release()+ return messages, _existing_system_prompt(agent, system_message)+ except BaseException:+ lease.release()+ raise_adopted = _adopt_if_parent_rotated(agent, lease, messages, system_message)if _adopted is not None:return _adopteddiff --git a/agent/conversation_compression_manual.py b/agent/conversation_compression_manual.pyindex 497b1999c2e..658cafc6fb8 100644--- a/agent/conversation_compression_manual.py+++ b/agent/conversation_compression_manual.py@@ -9,7 +9,7 @@ here so ``--preview`` / ``--aggressive`` and the lock-skip wording cannot driftfrom __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Any, Dict, List, Optional, Sequence+from typing import Any, Callable, Dict, List, Optional, Sequence#: Every surface renders the same refusal; hard truncation has no persistence path outside the guarded#: ``_compress_context`` rotation, so ``--aggressive`` is refused rather than mis-parsed as a focus topic.@@ -69,10 +69,13 @@ def estimate_request_tokens(agent: Any, messages: Sequence[Dict[str, Any]]) -> idef compress_now(agent: Any, history: Sequence[Dict[str, Any]], request: CompressRequest, *,system_message: Any = None, task_id: str = "default", skip_without_window: bool = False,+ snapshot_is_current: Optional[Callable[[], bool]] = None,) -> CompressResult:"""Run one manual compression of ``history`` on ``agent`` and return the outcome; the caller installs``after_messages`` (and re-anchors session ids) — history is never mutated here.+ ``snapshot_is_current`` validates the host's snapshot after durable lease admission, before the+ summarizer runs; the normal timeout/fallback pipeline remains in charge of the attempt.``preview=True`` performs no compression and leaves ``agent`` untouched. A held compression lockyields ``lock_skipped`` with the agent's signal cleared and the deferred context-engine notificationdiscarded; otherwise the caller must call ``finalize_context_engine_compression_notification(agent,@@ -126,6 +129,7 @@ def compress_now(compressed, _ = agent._compress_context(head, system_message, approx_tokens=before_tokens, focus_topic=request.focus_topic, force=True,defer_context_engine_notification=True, **({"task_id": task_id} if task_id != "default" else {}),+ **({"snapshot_is_current": snapshot_is_current} if snapshot_is_current is not None else {}),**({"verbatim_tail": tail_rows} if tail_rows else {}))except Exception:finalize_context_engine_compression_notification(agent, committed=False)diff --git a/tests/tui_gateway/test_manual_compress_history_fence.py b/tests/tui_gateway/test_manual_compress_history_fence.pynew file mode 100644index 00000000000..71271015a6d--- /dev/null+++ b/tests/tui_gateway/test_manual_compress_history_fence.py@@ -0,0 +1,92 @@+"""Manual compression must not publish a snapshot invalidated before lease admission."""+import threading+from unittest.mock import MagicMock++import pytest++[email protected]("in_place", [False, True])[email protected]("stale", [False, True, "validation_error", "empty_summary"])+def test_manual_compress_rejects_history_rewritten_before_admission(tmp_path, monkeypatch, stale, in_place):+ from hermes_state import SessionDB+ from run_agent import AIAgent+ from agent.context_compressor import SUMMARY_PREFIX+ from tui_gateway import server++ monkeypatch.setattr(server, "_get_usage", lambda agent: {})+ db = SessionDB(db_path=tmp_path / "state.db")+ parent = "manual-fence-parent"+ db.create_session(parent, source="cli")+ for i in range(12):+ db.append_message(parent, "user", f"question {i} " + "x" * 80)+ db.append_message(parent, "assistant", f"answer {i} " + "y" * 80)+ before = db.get_messages_as_conversation(parent)+ agent = AIAgent(api_key="fixture-only", base_url="http://127.0.0.1:9/v1",+ model="test/model", platform="cli", quiet_mode=True,+ session_db=db, session_id=parent, skip_context_files=True,+ skip_memory=True, enabled_toolsets=[])+ compressor = MagicMock()+ compressor.compress.return_value = [+ {"role": "user", "content": SUMMARY_PREFIX + " earlier turns"}, before[-1].copy()]+ compressor.compression_count = 1+ compressor.last_prompt_tokens = compressor.last_completion_tokens = 0+ compressor._last_summary_error = None+ compressor._last_compress_aborted = compressor._last_summary_auth_failure = False+ compressor._last_aux_model_failure_model = compressor._last_aux_model_failure_error = None+ agent.context_compressor = compressor+ agent.compression_in_place = in_place+ agent._compression_feasibility_checked = True+ monkeypatch.setattr(agent, "_build_system_prompt", lambda *args, **kwargs: "fixture prompt")+ session = {"agent": agent, "history_lock": threading.Lock(), "history": list(before),+ "history_version": 1, "running": False, "session_key": parent, "cwd": str(tmp_path)}+ if stale is True:+ # A real guarded edit wins after the host snapshot but before the durable lease.+ replacement = [{"role": "user", "content": "edited question"},+ {"role": "assistant", "content": "edited answer"}]+ acquire = db.try_acquire_compression_lock++ def edit_then_acquire(*args, **kwargs):+ with session["history_lock"]:+ db.replace_messages(parent, replacement, reject_active_turn_lease=True)+ session["history"] = replacement+ session["history_version"] += 1+ return acquire(*args, **kwargs)++ monkeypatch.setattr(db, "try_acquire_compression_lock", edit_then_acquire)+ try:+ if stale == "validation_error":+ from agent.conversation_compression_manual import compress_now, parse_compress_args++ def fail_validation():+ assert db.get_compression_lock_holder(parent) is not None+ raise RuntimeError("validation failed")++ with pytest.raises(RuntimeError, match="validation failed"):+ compress_now(agent, before, parse_compress_args(""), snapshot_is_current=fail_validation)+ assert db.get_compression_lock_holder(parent) is None+ assert agent.session_id == parent+ assert db.get_messages_as_conversation(parent) == before+ return+ if stale == "empty_summary":+ compressor.compress.return_value = []+ removed, _ = server._compress_session_history(session, before_messages=before, history_version=1)+ assert db.get_compression_lock_holder(parent) is None+ if stale is True:+ assert removed == 0+ assert agent.session_id == parent, "stale compression rotated the live agent"+ assert db.find_live_compression_child(parent) is None+ assert db.get_session(parent)["ended_at"] is None+ assert [m["content"] for m in db.get_messages_as_conversation(parent)] == [+ "edited question", "edited answer"]+ assert session["history"] == replacement+ elif stale == "empty_summary":+ assert removed == 0+ assert agent.session_id == parent+ assert session["history"] == before+ else:+ assert removed > 0+ assert (agent.session_id == parent) is in_place+ assert (db.find_live_compression_child(parent) is None) is in_place+ finally:+ agent.close()+ db.close()diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.pyindex 0c828efc466..033d9860a2d 100644--- a/tui_gateway/session_compression.py+++ b/tui_gateway/session_compression.py@@ -244,8 +244,13 @@ def _compress_session_history(# RPC thread: bind the session cwd, or the boundary prompt rebuild resolves the backend's cwd and# persists a prompt every other process then rejects as stale runtime (fresh build, no tools pin).tokens = _set_session_context(session.get("session_key") or "", cwd=_session_cwd(session))+ def snapshot_is_current():+ with session["history_lock"]:+ return int(session.get("history_version", 0)) == history_version+try:- result = compress_now(agent, before_messages, request, task_id=session.get("session_key") or "default")+ result = compress_now(agent, before_messages, request, task_id=session.get("session_key") or "default",+ snapshot_is_current=snapshot_is_current)finally:_clear_session_context(tokens)if result.status == "preview":