Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 49 additions & 23 deletions agent/conversation_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,38 @@ def _compression_lock_holder(agent: Any) -> str:
)


def _clear_compression_lock_defer(agent: Any) -> None:
agent._compression_deferred_by_lock = False
agent._compression_deferred_session_id = None
agent._compression_deferred_holder = None


def _mark_compression_lock_deferred(
agent: Any,
session_id: str,
holder: Optional[str],
) -> None:
agent._compression_deferred_by_lock = True
agent._compression_deferred_session_id = session_id
agent._compression_deferred_holder = holder


def _sync_session_context_after_compression(agent: Any) -> None:
"""Keep tool routing and log context aligned after compression rotation."""
try:
from gateway.session_context import set_current_session_id

set_current_session_id(agent.session_id)
except Exception:
os.environ["HERMES_SESSION_ID"] = agent.session_id
try:
from hermes_logging import set_session_context

set_session_context(agent.session_id)
except Exception:
pass


def check_compression_model_feasibility(agent: Any) -> None:
"""Warn at session start if the auxiliary compression model's context
window is smaller than the main model's compression threshold.
Expand Down Expand Up @@ -306,10 +338,13 @@ def compress_context(

Returns:
``(compressed_messages, new_system_prompt)`` tuple. When
compression aborts (aux LLM failed to produce a usable summary),
returns the original messages unchanged and the existing system
prompt β€” the session is NOT rotated. Callers should detect the
no-op via ``len(returned) == len(input)`` and stop the retry loop.
compression aborts (aux LLM failed to produce a usable summary) or
another path already owns the compression lock, returns the original
messages unchanged and the existing system prompt β€” the session is
NOT rotated. Lock contention also sets
``agent._compression_deferred_by_lock`` so callers can distinguish a
temporary concurrent-compression defer from real no-progress
compression.
"""
# Lazy feasibility check β€” run the auxiliary-provider probe + context
# length lookup just-in-time on the first compression attempt instead of
Expand Down Expand Up @@ -363,11 +398,12 @@ def compress_context(
# SessionEntry at the start of their own compression attempt.
#
# If we can't acquire the lock, another path is mid-compression on
# this session. Aborting is correct: the messages are unchanged, the
# other path's rotation will produce the canonical new session_id,
# and our caller's auto-compress loop sees ``len(returned) == len(input)``
# and stops retrying for this cycle. The session is NOT corrupted β€”
# we just sit out this round and let the winner finish.
# this session. Aborting is correct, but returning unchanged messages
# is not enough signal by itself: unchanged messages also mean "real
# compression failure/no progress". Mark lock contention explicitly so
# callers do not continue into a provider request with the same
# oversized transcript.
_clear_compression_lock_defer(agent)
_lock_db = getattr(agent, "_session_db", None)
_lock_sid = agent.session_id or ""
_lock_holder: Optional[str] = None
Expand Down Expand Up @@ -415,7 +451,7 @@ def compress_context(
existing = None
logger.warning(
"compression skipped: another path is compressing session=%s "
"(holder=%s) β€” returning messages unchanged to avoid session fork",
"(holder=%s) β€” deferring this compression attempt to avoid session fork",
_lock_sid, existing,
)
_lock_holder = None # don't release a lock we don't own
Expand All @@ -430,6 +466,7 @@ def compress_context(
)
except Exception:
pass
_mark_compression_lock_deferred(agent, _lock_sid, existing)
_existing_sp = getattr(agent, "_cached_system_prompt", None)
if not _existing_sp:
_existing_sp = agent._build_system_prompt(system_message)
Expand Down Expand Up @@ -570,27 +607,16 @@ def _release_lock() -> None:
agent.session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
# Ordering contract: the agent thread updates the contextvar here;
# the gateway propagates to SessionEntry after run_in_executor returns.
try:
from gateway.session_context import set_current_session_id

set_current_session_id(agent.session_id)
except Exception:
os.environ["HERMES_SESSION_ID"] = agent.session_id
# The gateway/tools session context (ContextVar + env) and the
# logging session context are SEPARATE mechanisms. The call above
# logging session context are SEPARATE mechanisms. The helper
# moves the former; the ``[session_id]`` tag on log lines comes
# from ``hermes_logging._session_context`` (set once per turn in
# conversation_loop.py). Without this, post-rotation log lines in
# the same turn keep the STALE old id while the message/DB/gateway
# state carry the new one β€” breaking log correlation exactly at the
# compaction boundary (see #34089). Guarded separately so a logging
# failure can never regress the routing update above.
try:
from hermes_logging import set_session_context

set_session_context(agent.session_id)
except Exception:
pass
_sync_session_context_after_compression(agent)
agent._session_db_created = False
agent._session_db.create_session(
session_id=agent.session_id,
Expand Down
66 changes: 66 additions & 0 deletions agent/conversation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,36 @@ def _content_policy_blocked_result(
}


def _compression_deferred_result(
agent,
messages: List[Dict],
conversation_history: Optional[List[Dict]],
api_call_count: int,
) -> Dict[str, Any]:
"""Return a soft stop when another path is compressing this session."""
session_id = getattr(agent, "_compression_deferred_session_id", None) or agent.session_id
holder = getattr(agent, "_compression_deferred_holder", None)
logger.info(
"turn deferred while compression lock is held: session=%s holder=%s",
session_id or "none",
holder,
)
try:
agent._flush_status_buffer()
except Exception:
pass
return {
"messages": messages,
"completed": False,
"api_calls": api_call_count,
"error": "Context compression is already running for this session. Retry after it finishes.",
"partial": True,
"failed": False,
"compression_deferred": True,
"session_id": agent.session_id,
}


def _sync_failover_system_message(agent, api_messages, active_system_prompt):
"""Refresh the in-flight system message after a provider failover.

Expand Down Expand Up @@ -560,6 +590,14 @@ def run_conversation(
_plugin_user_context = _ctx.plugin_user_context

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please carry this same deferral check to the current-main pre-API compaction path introduced by 90f84144e: it calls _compress_context() at agent/conversation_loop.py:1034 and otherwise continues toward request construction. Add a regression that pre-holds the lock and asserts no provider request is dispatched.

_ext_prefetch_cache = _ctx.ext_prefetch_cache

if _ctx.compression_deferred_by_lock:
return _compression_deferred_result(
agent,
messages,
conversation_history,
api_call_count=0,
)

# Main conversation loop counters (pure locals consumed by the loop below).
api_call_count = 0
final_response = None
Expand Down Expand Up @@ -2776,6 +2814,13 @@ def _perform_api_call(next_api_kwargs):
approx_tokens=approx_tokens,
task_id=effective_task_id,
)
if getattr(agent, "_compression_deferred_by_lock", False):
return _compression_deferred_result(
agent,
messages,
conversation_history,
api_call_count,
)
# Compression created a new session β€” clear history
# so _flush_messages_to_session_db writes compressed
# messages to the new session, not skipping them.
Expand Down Expand Up @@ -2987,6 +3032,13 @@ def _perform_api_call(next_api_kwargs):
messages, system_message, approx_tokens=approx_tokens,
task_id=effective_task_id,
)
if getattr(agent, "_compression_deferred_by_lock", False):
return _compression_deferred_result(
agent,
messages,
conversation_history,
api_call_count,
)
# Compression created a new session β€” clear history
# so _flush_messages_to_session_db writes compressed
# messages to the new session, not skipping them.
Expand Down Expand Up @@ -3143,6 +3195,13 @@ def _perform_api_call(next_api_kwargs):
messages, system_message, approx_tokens=approx_tokens,
task_id=effective_task_id,
)
if getattr(agent, "_compression_deferred_by_lock", False):
return _compression_deferred_result(
agent,
messages,
conversation_history,
api_call_count,
)
# Compression created a new session β€” clear history
# so _flush_messages_to_session_db writes compressed
# messages to the new session, not skipping them.
Expand Down Expand Up @@ -4130,6 +4189,13 @@ def _perform_api_call(next_api_kwargs):
approx_tokens=agent.context_compressor.last_prompt_tokens,
task_id=effective_task_id,
)
if getattr(agent, "_compression_deferred_by_lock", False):
return _compression_deferred_result(
agent,
messages,
conversation_history,
api_call_count,
)
# Compression created a new session β€” clear history so
# _flush_messages_to_session_db writes compressed messages
# to the new session (see preflight compression comment).
Expand Down
24 changes: 24 additions & 0 deletions agent/turn_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ class TurnContext:
plugin_user_context: str = ""
# External-memory prefetch result, reused across loop iterations.
ext_prefetch_cache: str = ""
# Preflight compression skipped because another path is already compressing
# this session. The caller should not proceed into a provider request with
# the unchanged oversized transcript.
compression_deferred_by_lock: bool = False
compression_deferred_session_id: Optional[str] = None


def build_turn_context(
Expand Down Expand Up @@ -147,6 +152,9 @@ def build_turn_context(
turn_id = f"{agent.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}"
agent._current_turn_id = turn_id
agent._current_api_request_id = ""
agent._compression_deferred_by_lock = False
agent._compression_deferred_session_id = None
agent._compression_deferred_holder = None

# Reset retry counters and iteration budget at the start of each turn.
agent._invalid_tool_retries = 0
Expand Down Expand Up @@ -317,6 +325,22 @@ def build_turn_context(
messages, system_message, approx_tokens=_preflight_tokens,
task_id=effective_task_id,
)
if getattr(agent, "_compression_deferred_by_lock", False):
return TurnContext(
user_message=user_message,
original_user_message=original_user_message,
messages=messages,
conversation_history=conversation_history,
active_system_prompt=active_system_prompt,
effective_task_id=effective_task_id,
turn_id=turn_id,
current_turn_user_idx=current_turn_user_idx,
should_review_memory=should_review_memory,
compression_deferred_by_lock=True,
compression_deferred_session_id=getattr(
agent, "_compression_deferred_session_id", None
),
)
if len(messages) >= _orig_len:
break # Cannot compress further
conversation_history = None
Expand Down
14 changes: 7 additions & 7 deletions tests/agent/test_compression_concurrent_fork.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from hermes_state import SessionDB


Expand Down Expand Up @@ -147,11 +145,11 @@ def run(agent):
def test_skipped_compression_returns_messages_unchanged(tmp_path: Path) -> None:
"""The loser of the lock race must return its input messages verbatim.

Callers (preflight compression in ``conversation_loop.py``) detect the
no-op via ``len(returned) == len(input)`` and stop the auto-compress
retry loop. If the skipped path returned the compressed view, that
detection would break and the caller would mutate the conversation
without going through state.db rotation.
Callers also need the explicit ``_compression_deferred_by_lock`` flag.
A no-op return alone is ambiguous: it can mean lock contention, an aux
compression failure, or real no-progress compression. The lock-loser path
must be distinguishable so gateway/browser turns do not continue into a
provider request with the unchanged oversized transcript.
"""
db = SessionDB(db_path=tmp_path / "state.db")
parent_sid = "LOSER_TEST"
Expand All @@ -169,6 +167,8 @@ def test_skipped_compression_returns_messages_unchanged(tmp_path: Path) -> None:
# Skipped: messages returned verbatim, no rotation
assert compressed is messages or compressed == messages
assert agent.session_id == parent_sid
assert agent._compression_deferred_by_lock is True
assert agent._compression_deferred_session_id == parent_sid
# Compressor was never called (the skip happens before .compress())
agent.context_compressor.compress.assert_not_called()

Expand Down
33 changes: 32 additions & 1 deletion tests/agent/test_turn_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,38 @@ def test_no_review_when_memory_disabled():
assert ctx.should_review_memory is False


def test_preflight_compression_lock_defer_stops_before_api_context():
agent = _FakeAgent()
agent.compression_enabled = True
agent.context_compressor = types.SimpleNamespace(
protect_first_n=0,
protect_last_n=0,
last_prompt_tokens=0,
threshold_tokens=1,
context_length=100_000,
should_defer_preflight_to_real_usage=lambda _tokens: False,
should_compress=lambda _tokens: True,
)

def _defer_compression(messages, system_message, **_kwargs):
agent._compression_deferred_by_lock = True
agent._compression_deferred_session_id = "sess-1"
return messages, "SYSTEM"

agent._compress_context = _defer_compression

ctx = _build(
agent,
conversation_history=[{"role": "user", "content": "old"}],
)

assert ctx.compression_deferred_by_lock is True
assert ctx.compression_deferred_session_id == "sess-1"
assert ctx.messages[-1] == {"role": "user", "content": "hello"}
assert ctx.plugin_user_context == ""
assert ctx.ext_prefetch_cache == ""


# ── Between-turns MCP refresh (cache-safe late-binding) ──────────────────────
#
# A slow MCP server that connects after the agent's build-time tool snapshot
Expand Down Expand Up @@ -258,4 +290,3 @@ def test_between_turns_refresh_no_churn_when_unchanged():
_build(agent)

assert agent.tools is same # not replaced β†’ no churn

Loading