The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): roll back mutating engine failures
mnajafian-nvbd6d576eba38
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 056d2c5c3df..34ddb905cc0 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -3179,7 +3179,7 @@ def _rebuild_system_prompt_at_boundary(agent: Any, system_message: str) -> str:def _salvage_or_refuse_grown_transcript(- agent: Any, messages: list, compressed: list, *, system_message: str, attempt_started_at: float,+ agent: Any, original_messages: list, compressed: list, *, system_message: str, attempt_started_at: float,attempt_snapshot: dict,) -> tuple[Optional[list], Optional[str]]:"""Anti-growth guard at the COMMIT SITE (in-place commits before the gateway can inspect).@@ -3193,13 +3193,13 @@ def _salvage_or_refuse_grown_transcript(# (#83339), but in-place compaction commits inside this method via archive_and_compact — before the# gateway can inspect the result — so the guard must live here to protect both paths. On growth, treat# the attempt as a no-op: the original transcript stays untouched and durable.- _rough_in = estimate_messages_tokens_rough(messages)+ _rough_in = estimate_messages_tokens_rough(original_messages)_rough_out = estimate_messages_tokens_rough(compressed)if _rough_out > _rough_in:# Todo refresh and user-turn anchoring run after the compressor's own size check# and can tip a break-even candidate; give it one mechanical salvage pass.from agent.context_compressor import salvage_grown_transcript- _salvaged = salvage_grown_transcript(messages, compressed, budget=_rough_in)+ _salvaged = salvage_grown_transcript(original_messages, compressed, budget=_rough_in)if _salvaged is not None:_salv_est = estimate_messages_tokens_rough(_salvaged)if _salv_est < _rough_in:@@ -3685,21 +3685,20 @@ def _commit_compaction(if agent._session_db:split_status = "pending"try:- # Memory extraction runs in BOTH modes: pre-compaction turns are summarized- # away whether or not the id rotates.- agent.commit_memory_session(messages)-# Pop _compaction_tail tags before the size estimate / rotation: they must not# inflate anti-growth or reach the provider. Track ids: salvage may subset list._tail_tagged_ids = {id(m) for m in compressed if isinstance(m, dict) and m.pop("_compaction_tail", None)}+ original_messages = messages_before_compression if messages_before_compression is not None else messagescompressed, _refused_sp = _salvage_or_refuse_grown_transcript(- agent, messages, compressed, system_message=system_message, attempt_started_at=attempt.started_at,- attempt_snapshot=attempt.snapshot,+ agent, original_messages, compressed, system_message=system_message,+ attempt_started_at=attempt.started_at, attempt_snapshot=attempt.snapshot,)if compressed is None:return _CommitOutcome(compressed=messages, refused_prompt=_refused_sp, commit_started_at=commit_started_at)+ # Publish memory only after every refusal gate, from the immutable pre-compression snapshot.+ agent.commit_memory_session(original_messages)from agent.context_compressor import PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY, stamp_db_persisted_markersfrom hermes_cli.partial_compress import rejoin_compressed_head_and_tailif in_place:@@ -3872,7 +3871,7 @@ def _run_summary_phase() -> _SummaryPhase:"""Adopt a grown durable parent, gather memory context and run the summarizer.A hard cancel restores the compressor snapshot + live list, records a stall backoff while the lease is- still held, and aborts; any other failure releases the lease and re-raises."""+ still held, and aborts; any other failure restores the live list, releases the lease and re-raises."""pre_msg_count = len(messages)_activity_heartbeat: Optional[_CompressionActivityHeartbeat] = Nonemessages_before_compression = None@@ -3940,7 +3939,7 @@ def _run_summary_phase()return _SummaryPhase(messages=messages, abort_prompt=_existing_system_prompt(agent, system_message))except BaseException as _compress_exc:- # Any failure after lock acquisition must release it or the session is permanently blocked from compression.+ _restore_messages_snapshot(messages, messages_before_compression)_stop_heartbeat("context compression failed")lease.release()_emit_aborted_attempt_telemetry(agent, attempt.started_at, f"exception:{type(_compress_exc).__name__}")diff --git a/tests/agent/test_compression_refusal_restores_transcript.py b/tests/agent/test_compression_refusal_restores_transcript.pyindex f29b3d3597b..cb3e05cdd66 100644--- a/tests/agent/test_compression_refusal_restores_transcript.py+++ b/tests/agent/test_compression_refusal_restores_transcript.py@@ -66,10 +66,26 @@ def _growing_engine(_compressor):return _compress+def _growing_in_place_engine(_compressor):+ def _compress(msgs, **_kw):+ msgs[:] = [{"role": "assistant", "content": "GROWN " * 20_000}]+ return msgs++ return _compress+++def _raising_engine(_compressor):+ def _compress(msgs, **_kw):+ msgs.clear()+ raise RuntimeError("context engine failed")++ return _compress++@pytest.mark.parametrize("make_engine",- [_aborting_engine, _empty_transcript_engine, _growing_engine],- ids=["compressor_aborted", "empty_transcript", "would_grow"],+ [_aborting_engine, _empty_transcript_engine, _growing_engine, _growing_in_place_engine],+ ids=["compressor_aborted", "empty_transcript", "would_grow", "would_grow_in_place"],)def test_refused_candidate_from_mutating_engine_returns_original_transcript(tmp_path: Path, make_engine@@ -83,20 +99,49 @@ def test_refused_candidate_from_mutating_engine_returns_original_transcript(messages = [{"role": "user", "content": f"m{i} " + "x" * 200} for i in range(21)]original = [dict(m) for m in messages]- with patch.object(type(compressor), "compress", side_effect=make_engine(compressor)), patch.object(- db, "archive_and_compact", wraps=db.archive_and_compact- ) as archive_and_compact:- # A caller-owned fence selects the direct path that gateway session hygiene uses.- returned, _sp = agent._compress_context(- messages, "sys", approx_tokens=120_000, commit_fence=CompressionCommitFence()- )+ try:+ with patch.object(type(compressor), "compress", side_effect=make_engine(compressor)), patch.object(+ agent, "commit_memory_session", wraps=agent.commit_memory_session+ ) as commit_memory_session, patch.object(+ db, "archive_and_compact", wraps=db.archive_and_compact+ ) as archive_and_compact:+ # A caller-owned fence selects the direct path that gateway session hygiene uses.+ returned, _sp = agent._compress_context(+ messages, "sys", approx_tokens=120_000, commit_fence=CompressionCommitFence()+ )++ commit_memory_session.assert_not_called()+ archive_and_compact.assert_not_called()+ assert returned == original+ assert messages == original+ assert agent.session_id == session_id+ assert db._conn.execute(+ "SELECT COUNT(*) FROM sessions WHERE parent_session_id = ?", (session_id,)+ ).fetchone()[0] == 0+ assert db.get_session(session_id)["end_reason"] is None+ assert db.get_compression_lock_holder(session_id) is None+ finally:+ agent.close()+++def test_raising_mutating_engine_restores_original_transcript(tmp_path: Path) -> None:+ db = SessionDB(db_path=tmp_path / "state.db")+ session_id = "RAISING_ENGINE"+ db.create_session(session_id, source="test")+ agent = _build_agent(db, session_id)+ compressor = agent.context_compressor+ messages = [{"role": "user", "content": f"m{i} " + "x" * 200} for i in range(21)]+ original = [dict(m) for m in messages]- assert returned == original- assert messages == original- assert agent.session_id == session_id- assert db._conn.execute(- "SELECT COUNT(*) FROM sessions WHERE parent_session_id = ?", (session_id,)- ).fetchone()[0] == 0- assert db.get_session(session_id)["end_reason"] is None- archive_and_compact.assert_not_called()- assert db.get_compression_lock_holder(session_id) is None+ try:+ with patch.object(type(compressor), "compress", side_effect=_raising_engine(compressor)):+ with pytest.raises(RuntimeError, match="context engine failed"):+ agent._compress_context(+ messages, "sys", approx_tokens=120_000, commit_fence=CompressionCommitFence()+ )+ assert messages == original+ assert agent.session_id == session_id+ assert db.get_session(session_id)["end_reason"] is None+ assert db.get_compression_lock_holder(session_id) is None+ finally:+ agent.close()