From 91af511c262072c917f36ed5fca9b2a3326d5f81 Mon Sep 17 00:00:00 2001 From: 3ASiC Date: Thu, 16 Jul 2026 23:48:09 +0800 Subject: [PATCH 1/3] fix(compression): reclaim locks from dead processes --- hermes_state.py | 81 +++++++++++++++++--- tests/test_hermes_state_compression_locks.py | 49 ++++++++++++ 2 files changed, 118 insertions(+), 12 deletions(-) diff --git a/hermes_state.py b/hermes_state.py index 1e39458229448..548f4e025080b 100644 --- a/hermes_state.py +++ b/hermes_state.py @@ -17,6 +17,7 @@ import asyncio import json import logging +import os import random import re import sqlite3 @@ -31,6 +32,36 @@ 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=``. 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. + """ + 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): + 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 @@ -2529,10 +2560,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 @@ -2544,12 +2575,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( @@ -2562,12 +2610,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", diff --git a/tests/test_hermes_state_compression_locks.py b/tests/test_hermes_state_compression_locks.py index 53e3bc0dec430..21b573dff100a 100644 --- a/tests/test_hermes_state_compression_locks.py +++ b/tests/test_hermes_state_compression_locks.py @@ -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 @@ -99,6 +101,53 @@ 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 + kill = monkeypatch.setattr( + hermes_state.os, + "kill", + lambda *_args: pytest.fail("unstructured holder must not probe a PID"), + ) + assert kill is None + assert db.try_acquire_compression_lock( + "sess1", "pid=525252:tid=2:agent=def:nonce=other", ttl_seconds=300 + ) is False + + # ---------------------------------------------------------------------- # Empty / invalid input # ---------------------------------------------------------------------- From ab5f70fd7b47778b07e56bf02f5dfa61df1957de Mon Sep 17 00:00:00 2001 From: 3ASiC Date: Thu, 16 Jul 2026 23:57:24 +0800 Subject: [PATCH 2/3] fix(compression): stop retrying no-op compactions --- agent/conversation_loop.py | 14 ++++++++++ tests/run_agent/test_run_agent.py | 43 +++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py index 420d12670e623..a03fd216e164d 100644 --- a/agent/conversation_loop.py +++ b/agent/conversation_loop.py @@ -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. diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.py index c218e75564ee6..b55328d65be47 100644 --- a/tests/run_agent/test_run_agent.py +++ b/tests/run_agent/test_run_agent.py @@ -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" From 437ee4ca3f22b6fd3208aff6eeb0239b728e870d Mon Sep 17 00:00:00 2001 From: 3ASiC Date: Fri, 17 Jul 2026 00:04:12 +0800 Subject: [PATCH 3/3] fix(compression): keep PID probing POSIX-only --- hermes_state.py | 7 ++++++- tests/test_hermes_state_compression_locks.py | 22 ++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/hermes_state.py b/hermes_state.py index 548f4e025080b..273881b44df4b 100644 --- a/hermes_state.py +++ b/hermes_state.py @@ -45,6 +45,11 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool: 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 @@ -58,7 +63,7 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool: os.kill(pid, 0) except ProcessLookupError: return True - except (PermissionError, OSError): + except (PermissionError, OSError, OverflowError): return False return False diff --git a/tests/test_hermes_state_compression_locks.py b/tests/test_hermes_state_compression_locks.py index 21b573dff100a..eb1e335b97874 100644 --- a/tests/test_hermes_state_compression_locks.py +++ b/tests/test_hermes_state_compression_locks.py @@ -137,12 +137,30 @@ def test_unstructured_holder_waits_for_ttl( assert db.try_acquire_compression_lock( "sess1", "legacy_holder", ttl_seconds=300 ) is True - kill = monkeypatch.setattr( + monkeypatch.setattr( hermes_state.os, "kill", lambda *_args: pytest.fail("unstructured holder must not probe a PID"), ) - assert kill is None + 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