Skip to content

The agent that grows with you

fix(sessions): briefly wait out a live compression lock instead of killing the turn

MaxFreedomPollard221be76e36de
diff --git a/hermes_state.py b/hermes_state.py
index 16473d9e3b3..077d2aa512e 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1529,6 +1529,22 @@ class CompressionSessionBusyError(RuntimeError):
"""A non-owner tried to write while compression owns the session."""
+class SessionCompressionInProgressError(CompressionSessionBusyError):
+ """A concurrent writer collided with a *live* compression lock.
+
+ Split out from :class:`CompressionSessionBusyError` because the two
+ conditions that class covers need opposite handling. This one is
+ transient: a healthy compressor holds the session for a few seconds and
+ the lock row carries its own ``expires_at``, so the write can simply wait
+ (see ``_execute_write``'s patience loop). The other case, a compressor
+ discovering its own lease is gone, is permanent and must fail fast rather
+ than spin out the whole patience budget.
+
+ Subclassing keeps every existing ``except CompressionSessionBusyError``
+ handler working unchanged.
+ """
+
+
def _connect_tracked_db(path, tracking_path=None, **kwargs):
"""``sqlite3.connect`` that registers the open fd for lock-safety.
@@ -1756,6 +1772,15 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# attempts.
_WRITE_PATIENCE_S = 20.0
_TRANSCRIPT_WRITE_PATIENCE_S = 60.0
+ # A live compression lock gets its own, much shorter budget than the write
+ # lock. Compression publishes in a couple of seconds, so a brief wait saves
+ # the overwhelming majority of concurrent turns (#75083). It deliberately
+ # stays short: the lease is a correctness boundary, not just a busy signal
+ # (see test_compression_lease_blocks_non_owner_but_allows_owner_flush), so
+ # a writer that is still locked out after this budget must still be
+ # refused rather than allowed to land a stale turn in a session whose
+ # compression is genuinely long-running or wedged.
+ _COMPRESSION_BUSY_WAIT_S = 5.0
_WRITE_RETRY_MIN_S = 0.020 # 20ms
_WRITE_RETRY_MAX_S = 0.150 # 150ms
_WRITE_RETRY_SLOW_AFTER_S = 2.0
@@ -2346,6 +2371,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if patience_s is None:
patience_s = self._WRITE_PATIENCE_S
deadline = time.monotonic() + patience_s
+ # Set on the first compression-busy collision so the short wait is
+ # measured from then, not from the start of the write.
+ compression_deadline: Optional[float] = None
while True:
try:
with self._lock:
@@ -2366,24 +2394,31 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if self._write_count % self._FTS_MERGE_EVERY_N_WRITES == 0:
self._try_incremental_merge_fts()
return result
+ except SessionCompressionInProgressError:
+ # A live foreign compression lock is transient: the compressor
+ # publishes in a couple of seconds. Without any wait, a steer
+ # that lands mid-compression aborts the user's turn as
+ # session_persistence_failed and sends the operator hunting
+ # disk space that was never the problem (#75083).
+ #
+ # The budget is _COMPRESSION_BUSY_WAIT_S, not the write-lock
+ # patience: the lease is a correctness boundary, so a writer
+ # still locked out after a short wait must be refused rather
+ # than left to land a stale turn once a long-running or wedged
+ # compression finally lets go.
+ if compression_deadline is None:
+ compression_deadline = min(
+ time.monotonic() + self._COMPRESSION_BUSY_WAIT_S, deadline
+ )
+ if self._sleep_before_write_retry(
+ compression_deadline, self._COMPRESSION_BUSY_WAIT_S
+ ):
+ continue
+ raise
except sqlite3.OperationalError as exc:
err_msg = str(exc).lower()
if "locked" in err_msg or "busy" in err_msg:
- now = time.monotonic()
- if now < deadline:
- elapsed = now - (deadline - patience_s)
- if elapsed >= self._WRITE_RETRY_SLOW_AFTER_S:
- jitter = random.uniform(
- self._WRITE_RETRY_SLOW_MIN_S,
- self._WRITE_RETRY_SLOW_MAX_S,
- )
- else:
- jitter = random.uniform(
- self._WRITE_RETRY_MIN_S,
- self._WRITE_RETRY_MAX_S,
- )
- # Never overshoot the deadline by a full slow-jitter.
- time.sleep(min(jitter, max(deadline - now, 0.001)))
+ if self._sleep_before_write_retry(deadline, patience_s):
continue
# Patience exhausted — say what actually happened so the
# surfaced error doesn't read as disk/permission damage.
@@ -2410,6 +2445,34 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
raise
continue
+ def _sleep_before_write_retry(
+ self, deadline: float, patience_s: float
+ ) -> bool:
+ """Sleep one jitter interval if the patience budget still allows it.
+
+ Returns True when the caller should retry, False when *deadline* has
+ passed and the error should propagate. Jitter stays small for the
+ first ``_WRITE_RETRY_SLOW_AFTER_S`` (fast reclaim on millisecond
+ contention) and backs off after that, and never overshoots the
+ deadline by a full slow-jitter.
+ """
+ now = time.monotonic()
+ if now >= deadline:
+ return False
+ elapsed = now - (deadline - patience_s)
+ if elapsed >= self._WRITE_RETRY_SLOW_AFTER_S:
+ jitter = random.uniform(
+ self._WRITE_RETRY_SLOW_MIN_S,
+ self._WRITE_RETRY_SLOW_MAX_S,
+ )
+ else:
+ jitter = random.uniform(
+ self._WRITE_RETRY_MIN_S,
+ self._WRITE_RETRY_MAX_S,
+ )
+ time.sleep(min(jitter, max(deadline - now, 0.001)))
+ return True
+
@staticmethod
def _is_fts_write_corruption_error(exc: sqlite3.DatabaseError) -> bool:
"""True for the error class a corrupt FTS index raises on writes.
@@ -5545,7 +5608,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
active_lock is not None
and active_lock["holder"] != compression_lock_holder
):
- raise CompressionSessionBusyError(
+ raise SessionCompressionInProgressError(
f"Session {session_id!r} is being compressed by another writer"
)
session = conn.execute(
diff --git a/tests/test_hermes_state_compression_busy_retry.py b/tests/test_hermes_state_compression_busy_retry.py
new file mode 100644
index 00000000000..5791040c400
--- /dev/null
+++ b/tests/test_hermes_state_compression_busy_retry.py
@@ -0,0 +1,129 @@
+"""A live compression lock must delay a concurrent append, not destroy the turn.
+
+``append_message`` refused immediately when another writer held the session's
+compression lock. The conversation loop turns that into
+``session_persistence_failed`` and tells the operator to check disk space and
+permissions, when in fact the store is healthy and busy for a few seconds.
+
+The write lock already gets a patience budget for exactly this reason (#74478).
+A compression hold is even more bounded, since the lock row carries its own
+``expires_at``, so the same budget applies here.
+
+The sibling condition, a compressor finding its own lease gone, is permanent
+and must still fail fast rather than spin out the whole budget.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_state import CompressionSessionBusyError, SessionDB
+
+
+def db(tmp_path: Path) -> SessionDB:
+ d = SessionDB(tmp_path / "state.db")
+ d.create_session("sess1", source="test")
+ return d
+
+
+def test_append_waits_out_a_live_compression_lock(db: SessionDB) -> None:
+ """The classic race: a steer lands while compression owns the session."""
+ assert db.try_acquire_compression_lock("sess1", "compressor") is True
+
+ released = threading.Event()
+
+ def _release_soon():
+ time.sleep(0.3)
+ db.release_compression_lock("sess1", "compressor")
+ released.set()
+
+ t = threading.Thread(target=_release_soon, daemon=True)
+ t.start()
+ try:
+ started = time.monotonic()
+ # No compression_lock_holder: this is an ordinary turn writer.
+ db.append_message("sess1", role="user", content="steered mid-compression")
+ elapsed = time.monotonic() - started
+ finally:
+ t.join(timeout=5)
+
+ assert released.is_set(), "test bug: lock was never released"
+ assert elapsed >= 0.25, "append returned before the lock could clear"
+ rows = db.get_messages("sess1")
+ assert any(r["content"] == "steered mid-compression" for r in rows), (
+ "the message the user sent was lost"
+ )
+
+
+def test_append_still_gives_up_when_the_lock_never_clears(
+ db: SessionDB, monkeypatch
+) -> None:
+ """The wait is bounded: a lock that never clears is still refused.
+
+ The lease is a correctness boundary, so a genuinely long-running or wedged
+ compression must not end with a stale turn landing in the parent.
+ """
+ monkeypatch.setattr(SessionDB, "_COMPRESSION_BUSY_WAIT_S", 0.5)
+ assert db.try_acquire_compression_lock("sess1", "compressor") is True
+
+ started = time.monotonic()
+ with pytest.raises(CompressionSessionBusyError):
+ db.append_message("sess1", role="user", content="never lands")
+ elapsed = time.monotonic() - started
+
+ assert elapsed >= 0.4, "gave up before spending the patience budget"
+ assert elapsed < 10, "did not give up within a bounded time"
+
+
+def test_the_lock_owner_is_never_delayed_by_its_own_lock(db: SessionDB) -> None:
+ assert db.try_acquire_compression_lock("sess1", "compressor") is True
+
+ started = time.monotonic()
+ db.append_message(
+ "sess1",
+ role="assistant",
+ content="written by the compressor",
+ compression_lock_holder="compressor",
+ )
+ assert time.monotonic() - started < 0.2
+
+
+def test_transient_error_is_a_subclass_of_the_original(db: SessionDB) -> None:
+ """Existing `except CompressionSessionBusyError` handlers must still catch."""
+ from hermes_state import SessionCompressionInProgressError
+
+ assert issubclass(SessionCompressionInProgressError, CompressionSessionBusyError)
+
+
+def test_no_lock_means_no_delay(db: SessionDB) -> None:
+ started = time.monotonic()
+ db.append_message("sess1", role="user", content="uncontended")
+ assert time.monotonic() - started < 0.2
+
+
+def test_a_lost_compression_lease_still_fails_fast(db: SessionDB) -> None:
+ """The other CompressionSessionBusyError case must NOT be retried.
+
+ ``publish_compression_child`` raises the same base class when the
+ compressor discovers its own lease is gone. That is permanent, so
+ retrying would burn the whole patience budget before failing anyway.
+ Only the transient subclass raised by ``append_message`` is retried.
+ """
+ started = time.monotonic()
+ with pytest.raises(CompressionSessionBusyError):
+ db.publish_compression_child(
+ parent_session_id="sess1",
+ child_session_id="child1",
+ source="test",
+ messages=[{"role": "user", "content": "compacted"}],
+ compression_lock_holder="not-the-holder",
+ require_compression_lease=True,
+ )
+ assert time.monotonic() - started < 0.5, (
+ "a lost lease is permanent and must not spend the retry budget"
+ )