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
14 changes: 14 additions & 0 deletions agent/conversation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1062,12 +1062,26 @@ def run_conversation(
f"📦 Pre-API compression: ~{request_pressure_tokens:,} tokens "
f"near the context/output limit. Compacting before the next model call."
)
pre_compression_message_count = len(messages)
messages, active_system_prompt = agent._compress_context(
messages,
system_message,
approx_tokens=request_pressure_tokens,
task_id=effective_task_id,
)
if len(messages) >= pre_compression_message_count:
# _compress_context documents an unchanged message count as a
# no-op (most importantly, another path owns the session's
# compression lock). Do not immediately call it two more times
# with the same transcript and spam three identical lifecycle
# messages. The request proceeds through the existing provider
# path, which preserves historical behavior after the old
# three-attempt backstop was exhausted.
compression_attempts = 3
logger.info(
"Pre-API compression made no progress; suppressing "
"duplicate attempts for this turn"
)
# Reset retry/empty-response state so the compacted request
# gets a fresh chance instead of inheriting stale recovery
# counters from the pre-compaction history.
Expand Down
86 changes: 74 additions & 12 deletions hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import asyncio
import json
import logging
import os
import random
import re
import sqlite3
Expand All @@ -31,6 +32,41 @@

logger = logging.getLogger(__name__)

_COMPRESSION_LOCK_HOLDER_PID_RE = re.compile(r"(?:^|:)pid=(\d+)(?::|$)")


def _compression_lock_holder_process_is_dead(holder: str) -> bool:
"""Return True only when a structured lock holder's local PID is gone.

Compression locks are stored in a host-local SQLite database and holder
IDs created by ``conversation_compression`` start with ``pid=<n>``. A
process killed during gateway shutdown cannot release its lease, so waiting
for the full TTL makes every new turn repeatedly attempt compaction. Reclaim
only when the kernel proves that PID no longer exists; legacy/unstructured
holders and permission errors remain protected until normal TTL expiry.
"""
# Python's os.kill(pid, 0) is a non-destructive liveness probe on POSIX.
# On Windows, any non-CTRL signal value is implemented with
# TerminateProcess, so fall back to TTL-only recovery there.
if os.name == "nt":
return False
match = _COMPRESSION_LOCK_HOLDER_PID_RE.search(holder or "")
if match is None:
return False
try:
pid = int(match.group(1))
except (TypeError, ValueError):
return False
if pid <= 0:
return False
try:
os.kill(pid, 0)
except ProcessLookupError:
return True
except (PermissionError, OSError, OverflowError):
return False
return False


def workspace_key(row: Dict[str, Any]) -> Optional[str]:
"""A session's workspace grouping key: its git repo root when known, else
Expand Down Expand Up @@ -2529,10 +2565,10 @@ def try_acquire_compression_lock(
MUST NOT proceed with compression in that case (its rotation would
race against the holder's, splitting the session lineage).

Expired locks (``expires_at < now``) are reclaimed transparently:
the stale row is deleted and the new holder acquires it. This
prevents a crashed compressor from permanently blocking the
session.
Expired locks (``expires_at < now``) are reclaimed transparently.
Structured holders whose local ``pid=`` no longer exists are reclaimed
immediately, so a gateway killed during compression does not stall the
replacement process for the full lease TTL.

Implementation: single-transaction DELETE-expired + INSERT-or-IGNORE,
followed by a SELECT to confirm we got the row. SQLite serialises
Expand All @@ -2544,12 +2580,29 @@ def try_acquire_compression_lock(
expires_at = now + ttl_seconds

def _do(conn):
# First: reclaim any expired lock for this session_id.
conn.execute(
"DELETE FROM compression_locks "
"WHERE session_id = ? AND expires_at < ?",
(session_id, now),
)
reclaimed_holder = None
row = conn.execute(
"SELECT holder, expires_at FROM compression_locks "
"WHERE session_id = ?",
(session_id,),
).fetchone()
if row is not None:
current_holder = (
row["holder"] if isinstance(row, sqlite3.Row) else row[0]
)
current_expires_at = (
row["expires_at"] if isinstance(row, sqlite3.Row) else row[1]
)
if (
current_expires_at < now
or _compression_lock_holder_process_is_dead(current_holder)
):
conn.execute(
"DELETE FROM compression_locks "
"WHERE session_id = ? AND holder = ?",
(session_id, current_holder),
)
reclaimed_holder = current_holder
# Then: try to insert. INSERT OR IGNORE returns no rowcount
# difference — verify ownership via SELECT.
conn.execute(
Expand All @@ -2562,12 +2615,21 @@ def _do(conn):
"SELECT holder FROM compression_locks WHERE session_id = ?",
(session_id,),
).fetchone()
return row is not None and (
acquired = row is not None and (
row["holder"] if isinstance(row, sqlite3.Row) else row[0]
) == holder
return acquired, reclaimed_holder

try:
return bool(self._execute_write(_do))
acquired, reclaimed_holder = self._execute_write(_do)
if reclaimed_holder:
logger.warning(
"Reclaimed stale compression lock for session=%s "
"(holder=%s)",
session_id,
reclaimed_holder,
)
return bool(acquired)
except sqlite3.Error as exc:
logger.warning(
"try_acquire_compression_lock(%s) failed: %s",
Expand Down
43 changes: 43 additions & 0 deletions tests/run_agent/test_run_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4228,6 +4228,49 @@ def _fake_activate(reason=None):
assert hook_events[0]["retryable"] is False
assert hook_events[0]["reason"] == FailoverReason.content_policy_blocked.value

def test_pre_api_compression_noop_is_not_retried_three_times(self, agent):
"""A contended/no-op compression emits one attempt, not three."""
self._setup_agent(agent)
agent.compression_enabled = True
agent.context_compressor.should_compress = MagicMock(return_value=True)
agent.context_compressor.should_defer_preflight_to_real_usage = MagicMock(
return_value=False
)
agent.context_compressor.get_active_compression_failure_cooldown = MagicMock(
return_value=None
)
response = _mock_response(content="Continued", finish_reason="stop")
agent.client.chat.completions.create.return_value = response

def no_op_compression(messages, *_args, **_kwargs):
return messages, agent._cached_system_prompt

with (
patch(
"agent.conversation_loop.estimate_request_tokens_rough",
return_value=241_007,
),
patch.object(
agent,
"_compress_context",
side_effect=no_op_compression,
) as mock_compress,
patch.object(agent, "_persist_session"),
patch.object(agent, "_save_trajectory"),
patch.object(agent, "_cleanup_task_resources"),
):
result = agent.run_conversation(
"hello",
conversation_history=[
{"role": "user", "content": "earlier"},
{"role": "assistant", "content": "earlier reply"},
],
)

assert result["final_response"] == "Continued"
assert mock_compress.call_count == 1
assert agent.client.chat.completions.create.call_count == 1

def test_ollama_small_runtime_context_fails_before_api_call(self, agent, caplog):
self._setup_agent(agent)
agent.model = "qwen3.5:9b"
Expand Down
67 changes: 67 additions & 0 deletions tests/test_hermes_state_compression_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@

from __future__ import annotations

import os
import threading
import time
from pathlib import Path

import pytest

import hermes_state
from hermes_state import SessionDB


Expand Down Expand Up @@ -99,6 +101,71 @@ def test_non_expired_lock_is_held(db: SessionDB) -> None:
assert db.try_acquire_compression_lock("sess1", "holder2") is False


def test_non_expired_lock_from_dead_pid_is_reclaimed(
db: SessionDB, monkeypatch: pytest.MonkeyPatch
) -> None:
dead_holder = "pid=424242:tid=1:agent=abc:nonce=deadbeef"
assert db.try_acquire_compression_lock(
"sess1", dead_holder, ttl_seconds=300
) is True

def process_is_gone(pid: int, signal: int) -> None:
assert pid == 424242
assert signal == 0
raise ProcessLookupError

monkeypatch.setattr(hermes_state.os, "kill", process_is_gone)

assert db.try_acquire_compression_lock(
"sess1", "pid=525252:tid=2:agent=def:nonce=fresh", ttl_seconds=300
) is True


def test_non_expired_lock_from_live_pid_is_not_reclaimed(db: SessionDB) -> None:
live_holder = f"pid={os.getpid()}:tid=1:agent=abc:nonce=live"
assert db.try_acquire_compression_lock(
"sess1", live_holder, ttl_seconds=300
) is True
assert db.try_acquire_compression_lock(
"sess1", "pid=525252:tid=2:agent=def:nonce=other", ttl_seconds=300
) is False


def test_unstructured_holder_waits_for_ttl(
db: SessionDB, monkeypatch: pytest.MonkeyPatch
) -> None:
assert db.try_acquire_compression_lock(
"sess1", "legacy_holder", ttl_seconds=300
) is True
monkeypatch.setattr(
hermes_state.os,
"kill",
lambda *_args: pytest.fail("unstructured holder must not probe a PID"),
)
assert db.try_acquire_compression_lock(
"sess1", "pid=525252:tid=2:agent=def:nonce=other", ttl_seconds=300
) is False


def test_windows_uses_ttl_only_without_os_kill(
db: SessionDB, monkeypatch: pytest.MonkeyPatch
) -> None:
holder = "pid=424242:tid=1:agent=abc:nonce=windows"
assert db.try_acquire_compression_lock(
"sess1", holder, ttl_seconds=300
) is True
monkeypatch.setattr(hermes_state.os, "name", "nt")
monkeypatch.setattr(
hermes_state.os,
"kill",
lambda *_args: pytest.fail("Windows must not use os.kill as a PID probe"),
)

assert db.try_acquire_compression_lock(
"sess1", "pid=525252:tid=2:agent=def:nonce=other", ttl_seconds=300
) is False


# ----------------------------------------------------------------------
# Empty / invalid input
# ----------------------------------------------------------------------
Expand Down