Skip to content

The agent that grows with you

fix(compression): watermark commit — appends flow freely, concurrent tail survives compaction

Teknium21d3e6370232
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index ad28602f10e..047325e97b6 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -2451,6 +2451,9 @@ def compress_context(
_lock_db = getattr(agent, "_session_db", None)
_lock_sid = agent.session_id or ""
_lock_holder: Optional[str] = None
+ # Watermark captured at compression start (#75316); None = fall back to
+ # archive-everything (no concurrent-tail preservation this cycle).
+ _commit_watermark: Optional[int] = None
# Probe whether the lock subsystem is actually available on this
# SessionDB instance. A process running mismatched module versions can have
# this call site while its long-lived SessionDB instance predates the lock
@@ -2555,6 +2558,27 @@ def compress_context(
_lock_acquired = _try_acquire_lock(
_lock_sid, _lock_holder, ttl_seconds=_lock_ttl
)
+ if _lock_acquired:
+ # Watermark (#75316): MAX(id) of active rows at compression
+ # START. Appends are NOT blocked while the slow provider
+ # summary runs — any row landing after this point is
+ # concurrent tail, and archive_and_compact() re-sequences
+ # it after the compacted set instead of archiving it.
+ try:
+ _commit_watermark = _lock_db.get_active_message_watermark(
+ _lock_sid
+ )
+ except Exception as _wm_err:
+ # Watermark capture is safety-additive: without it the
+ # commit falls back to archive-everything (historical
+ # behavior), so failure here must not abort compression.
+ logger.warning(
+ "compression watermark capture failed for "
+ "session=%s (%s) — concurrent appends this cycle "
+ "will be archived with the snapshot",
+ _lock_sid, _wm_err,
+ )
+ _commit_watermark = None
except Exception as _lock_err:
# The method exists and entered its implementation but failed.
# Do not mistake an internal AttributeError or TypeError for
@@ -3422,6 +3446,8 @@ def compress_context(
model_config_patch={
PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY: None,
},
+ watermark=_commit_watermark,
+ lock_holder=_lock_holder,
)
split_status = "in_place_committed"
# Reset the flush identity set so the next turn's appends are
diff --git a/hermes_state.py b/hermes_state.py
index 1f3c92d681b..5148a8e29ee 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -8965,18 +8965,16 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
(this guard has already needed targeted fixes — see the #74478
patience note below).
"""
- active_lock = conn.execute(
- "SELECT holder FROM compression_locks "
- "WHERE session_id = ? AND expires_at > ?",
- (session_id, time.time()),
- ).fetchone()
- if (
- active_lock is not None
- and active_lock["holder"] != compression_lock_holder
- ):
- raise SessionCompressionInProgressError(
- f"Session {session_id!r} is being compressed by another writer"
- )
+ # NOTE (#75316 redesign): appends do NOT check compression_locks.
+ # The lock's job is to stop two COMPRESSIONS colliding, not to fence
+ # ordinary transcript writes. Concurrent appends during a compression
+ # are safe by construction: archive_and_compact() commits against a
+ # watermark captured at compression start and clones every row that
+ # arrived after it back into the live transcript, in the same write
+ # transaction. Blocking appends here was the root cause of a whole
+ # symptom family — turns dying as session_persistence_failed while a
+ # slow provider summary held the lease (#74568, #77386), including
+ # stale locks from dead PIDs blocking writes for the full TTL.
if turn_lease_holder:
conversation_id = self._session_turn_lease_key_on_conn(conn, session_id)
lease = conn.execute(
@@ -9720,18 +9718,38 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
return cursor.fetchone() is not None
+ def get_active_message_watermark(self, session_id: str) -> int:
+ """MAX(id) of the session's active rows — the compression watermark.
+
+ Captured at compression START (before the slow provider summary call).
+ Every active row with ``id > watermark`` at commit time arrived
+ concurrently and must survive the compaction verbatim. Returns 0 for
+ an empty/unknown session.
+ """
+ if not session_id:
+ return 0
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ "SELECT COALESCE(MAX(id), 0) FROM messages "
+ "WHERE session_id = ? AND active = 1",
+ (session_id,),
+ ).fetchone()
+ return int(row[0]) if row else 0
+
def archive_and_compact(
self,
session_id: str,
compacted_messages: List[Dict[str, Any]],
model_config_patch: Optional[Dict[str, Any]] = None,
+ watermark: Optional[int] = None,
+ lock_holder: Optional[str] = None,
) -> int:
"""Non-destructive in-place compaction for a single durable session id.
- Soft-archives every currently-active message (``active = 0``) and
- inserts *compacted_messages* as fresh active rows — atomically, in one
- write transaction. The conversation keeps ONE session id for life
- (#38763) WITHOUT destroying history:
+ Soft-archives the active messages (``active = 0``) and inserts
+ *compacted_messages* as fresh active rows — atomically, in one write
+ transaction. The conversation keeps ONE session id for life (#38763)
+ WITHOUT destroying history:
- The live-context load (:meth:`get_messages_as_conversation`,
:meth:`get_messages`) filters ``active = 1`` by default, so the model
@@ -9745,14 +9763,48 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
flipping to active=0 is a content-preserving UPDATE) and are
recoverable via get_messages(..., include_inactive=True).
- This is the durability-preserving alternative to :meth:`replace_messages`
- for compaction. ``message_count`` is set to the ACTIVE (compacted) count,
- matching what the live load returns. ``model_config_patch`` is merged
- into the session's JSON config in the same transaction; a ``None``
- value removes that key. Returns the new active count.
+ Concurrent-append safety (#75316): when *watermark* is provided (the
+ value of :meth:`get_active_message_watermark` captured at compression
+ START), rows that arrived during the slow provider summary call
+ (``id > watermark``) are NOT summarized away. They are re-sequenced
+ after the compacted set by a pure-SQL column clone (every column
+ except ``id`` — content, api_content, platform_message_id, token
+ counts, reasoning sidecars all survive byte-exact, and the FTS
+ triggers index the clones naturally), and the originals are archived.
+ NOTE: re-sequencing assigns the tail rows fresh ids; consumers that
+ reference durable row ids re-resolve by content (see 3e8ab0610).
+ ``watermark=None`` preserves the historical archive-everything
+ behavior.
+
+ Commit-fence safety: when *lock_holder* is provided, the commit
+ verifies INSIDE the transaction that the compression lock is still
+ held by that holder and unexpired — a compression whose lease was
+ reclaimed (crash cleanup, TTL expiry, competing writer) fails the
+ commit instead of clobbering the winner's transcript.
+
+ ``message_count`` is set to the ACTIVE count after commit, matching
+ what the live load returns. ``model_config_patch`` is merged into the
+ session's JSON config in the same transaction; a ``None`` value
+ removes that key. Returns the new active count.
"""
def _do(conn):
+ if lock_holder is not None:
+ lock_row = conn.execute(
+ "SELECT holder, expires_at FROM compression_locks "
+ "WHERE session_id = ?",
+ (session_id,),
+ ).fetchone()
+ if (
+ lock_row is None
+ or lock_row["holder"] != lock_holder
+ or float(lock_row["expires_at"]) <= time.time()
+ ):
+ raise SessionCompressionInProgressError(
+ f"Compression lease for {session_id!r} lost before "
+ "commit; refusing to publish a stale compaction"
+ )
+
patched_model_config = None
if model_config_patch is not None:
# on_missing="raise": a prune/compaction must not commit
@@ -9763,12 +9815,34 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
conn, session_id, model_config_patch, on_missing="raise"
)
+ # Concurrent tail: active rows that arrived after the watermark.
+ # Snapshot their ids and tool_calls now — the clone below needs a
+ # stable id list, and the tool-call count keeps sessions.* honest.
+ tail_ids: list[int] = []
+ tail_tool_calls = 0
+ if watermark is not None:
+ for row in conn.execute(
+ "SELECT id, tool_calls FROM messages "
+ "WHERE session_id = ? AND active = 1 AND id > ? "
+ "ORDER BY id",
+ (session_id, int(watermark)),
+ ).fetchall():
+ tail_ids.append(int(row["id"]))
+ raw = row["tool_calls"]
+ if raw:
+ try:
+ parsed = json.loads(raw) if isinstance(raw, str) else raw
+ tail_tool_calls += len(parsed) if isinstance(parsed, list) else 0
+ except (TypeError, ValueError):
+ pass
+
# Soft-archive the live turns: active=0 hides them from the live
# context load, compacted=1 marks them as "summarized away" (vs
# rewind/undo's active=0+compacted=0, which means "user took it
# back"). search_messages includes compacted=1 rows by default so
# the pre-compaction transcript stays discoverable; live-context
- # loads (active=1 only) still exclude them.
+ # loads (active=1 only) still exclude them. Tail originals are
+ # archived too — their clones (below) carry the live copy.
conn.execute(
"UPDATE messages SET active = 0, compacted = 1 "
"WHERE session_id = ? AND active = 1",
@@ -9777,6 +9851,26 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
inserted, tool_calls_total = self._insert_message_rows(
conn, session_id, compacted_messages
)
+
+ if tail_ids:
+ # Re-sequence the concurrent tail after the compacted set via
+ # a pure-SQL column clone: no decode/re-encode round trip, no
+ # field drift — new id, active=1, compacted=0, all else exact.
+ placeholders = ",".join("?" for _ in tail_ids)
+ clone_cols = [
+ c for c in self._message_column_names(conn)
+ if c not in ("id", "active", "compacted")
+ ]
+ col_list = ", ".join(clone_cols)
+ conn.execute(
+ f"INSERT INTO messages ({col_list}, active, compacted) "
+ f"SELECT {col_list}, 1, 0 FROM messages "
+ f"WHERE id IN ({placeholders}) ORDER BY id",
+ tail_ids,
+ )
+ inserted += len(tail_ids)
+ tool_calls_total += tail_tool_calls
+
# message_count / tool_call_count reflect the LIVE (active) set —
# the archived rows are still on disk but not part of the live count.
if model_config_patch is None:
@@ -9794,6 +9888,15 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return self._execute_write(_do)
+ def _message_column_names(self, conn) -> List[str]:
+ """Column names of the messages table, cached per-connection era."""
+ cached = getattr(self, "_message_columns_cache", None)
+ if cached:
+ return cached
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()]
+ self._message_columns_cache = cols
+ return cols
+
def set_latest_user_api_content(
self, session_id: str, content: Any, api_content: str
) -> int:
diff --git a/tests/test_compression_watermark_commit.py b/tests/test_compression_watermark_commit.py
new file mode 100644
index 00000000000..f870452269c
--- /dev/null
+++ b/tests/test_compression_watermark_commit.py
@@ -0,0 +1,228 @@
+"""Watermark commit: concurrent appends survive in-place compaction (#75316).
+
+The provider summary call is external and slow. Messages that arrive while it
+runs must (a) persist immediately — appends are not fenced by the compression
+lock — and (b) survive the commit: ``archive_and_compact(watermark=...)``
+re-sequences every active row above the watermark after the compacted set
+instead of archiving it. The commit is holder-fenced: a compression whose
+lease was reclaimed cannot publish a stale compaction.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_state import SessionCompressionInProgressError, SessionDB
+
+
+def db(tmp_path: Path) -> SessionDB:
+ d = SessionDB(tmp_path / "state.db")
+ d.create_session("sess1", source="test")
+ return d
+
+
+def _seed(db: SessionDB, n: int = 6) -> None:
+ for i in range(n):
+ role = "user" if i % 2 == 0 else "assistant"
+ db.append_message("sess1", role=role, content=f"turn {i}")
+
+
+SUMMARY = [
+ {"role": "user", "content": "[CONTEXT COMPACTION] summary of turns 0-5"},
+ {"role": "assistant", "content": "Continuing from the summary."},
+]
+
+
+class TestWatermarkCommit:
+ def test_concurrent_tail_survives_compaction(self, db: SessionDB) -> None:
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ # Simulate the slow summary window: two messages land after capture.
+ db.append_message("sess1", role="user", content="mid-compression steer")
+ db.append_message("sess1", role="assistant", content="mid-compression reply")
+
+ count = db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+
+ live = db.get_messages("sess1")
+ contents = [r["content"] for r in live]
+ assert contents == [
+ "[CONTEXT COMPACTION] summary of turns 0-5",
+ "Continuing from the summary.",
+ "mid-compression steer",
+ "mid-compression reply",
+ ], "tail must follow the summary, in arrival order"
+ assert count == 4
+
+ def test_tail_clone_preserves_every_column(self, db: SessionDB) -> None:
+ """The pure-SQL clone must carry sidecar fields byte-exact."""
+ _seed(db, 2)
+ watermark = db.get_active_message_watermark("sess1")
+ db.append_message(
+ "sess1",
+ role="assistant",
+ content="tool caller",
+ tool_calls=[{"id": "c1", "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"}}],
+ )
+ db.append_message(
+ "sess1", role="tool", content="tool output",
+ tool_call_id="c1", tool_name="terminal",
+ )
+
+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+
+ live = db.get_messages("sess1")
+ by_content = {r["content"]: r for r in live}
+ caller = by_content["tool caller"]
+ result = by_content["tool output"]
+ parsed = caller["tool_calls"]
+ if isinstance(parsed, str):
+ parsed = json.loads(parsed)
+ assert parsed and parsed[0]["id"] == "c1"
+ assert result["tool_call_id"] == "c1"
+ assert result["tool_name"] == "terminal"
+
+ def test_conversation_load_is_correct_after_commit(self, db: SessionDB) -> None:
+ """The live conversation projection sees summary + tail, in order."""
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ db.append_message("sess1", role="user", content="late arrival")
+
+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+
+ convo = db.get_messages_as_conversation("sess1")
+ assert [m["content"] for m in convo] == [
+ "[CONTEXT COMPACTION] summary of turns 0-5",
+ "Continuing from the summary.",
+ "late arrival",
+ ]
+
+ def test_no_tail_behaves_identically_to_legacy(self, db: SessionDB) -> None:
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ count = db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+ assert count == 2
+ assert [r["content"] for r in db.get_messages("sess1")] == [
+ SUMMARY[0]["content"], SUMMARY[1]["content"],
+ ]
+
+ def test_none_watermark_preserves_historical_behavior(self, db: SessionDB) -> None:
+ """watermark=None archives everything — the pre-#75316 contract."""
+ _seed(db)
+ db.append_message("sess1", role="user", content="gets archived")
+ count = db.archive_and_compact("sess1", SUMMARY, watermark=None)
+ assert count == 2
+ contents = [r["content"] for r in db.get_messages("sess1")]
+ assert "gets archived" not in contents
+
+ def test_archived_rows_stay_recoverable(self, db: SessionDB) -> None:
+ """Originals (snapshot AND tail source rows) survive as archived."""
+ _seed(db, 4)
+ watermark = db.get_active_message_watermark("sess1")
+ db.append_message("sess1", role="user", content="tail row")
+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+
+ everything = db.get_messages("sess1", include_inactive=True)
+ archived = [r for r in everything if not r["active"]]
+ assert sum(1 for r in archived if r["content"] == "turn 0") == 1
+ # The tail original is archived; its clone is the live copy.
+ tail_rows = [r for r in everything if r["content"] == "tail row"]
+ assert sorted(bool(r["active"]) for r in tail_rows) == [False, True]
+
+ def test_session_counters_include_tail(self, db: SessionDB) -> None:
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ db.append_message(
+ "sess1", role="assistant", content="tail with tools",
+ tool_calls=[{"id": "t1", "type": "function",
+ "function": {"name": "x", "arguments": "{}"}}],
+ )
+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+ info = db.get_session("sess1")
+ assert info["message_count"] == 3
+ assert info["tool_call_count"] == 1
+
+
+class TestCommitFence:
+ def test_commit_refused_when_lease_lost(self, db: SessionDB) -> None:
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ assert db.try_acquire_compression_lock("sess1", "worker-A") is True
+ # Lease reclaimed by another writer while worker-A's summary ran.
+ db.release_compression_lock("sess1", "worker-A")
+ assert db.try_acquire_compression_lock("sess1", "worker-B") is True
+
+ with pytest.raises(SessionCompressionInProgressError):
+ db.archive_and_compact(
+ "sess1", SUMMARY, watermark=watermark, lock_holder="worker-A"
+ )
+ # Nothing committed: original transcript intact.
+ assert [r["content"] for r in db.get_messages("sess1")] == [
+ f"turn {i}" for i in range(6)
+ ]
+
+ def test_commit_refused_when_lease_expired(self, db: SessionDB) -> None:
+ _seed(db)
+ assert db.try_acquire_compression_lock(
+ "sess1", "worker-A", ttl_seconds=0.05
+ ) is True
+ time.sleep(0.1)
+ with pytest.raises(SessionCompressionInProgressError):
+ db.archive_and_compact("sess1", SUMMARY, lock_holder="worker-A")
+
+ def test_commit_allowed_for_live_holder(self, db: SessionDB) -> None:
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+ assert db.try_acquire_compression_lock("sess1", "worker-A") is True
+ count = db.archive_and_compact(
+ "sess1", SUMMARY, watermark=watermark, lock_holder="worker-A"
+ )
+ assert count == 2
+
+ def test_refused_commit_rolls_back_atomically(self, db: SessionDB) -> None:
+ """Failure injection: the fence raise must leave zero partial writes."""
+ _seed(db)
+ before = db.get_messages("sess1", include_inactive=True)
+ with pytest.raises(SessionCompressionInProgressError):
+ db.archive_and_compact("sess1", SUMMARY, lock_holder="never-held")
+ after = db.get_messages("sess1", include_inactive=True)
+ assert len(before) == len(after)
+ assert all(r["active"] for r in after)
+
+
+class TestConcurrentAppendDuringCompaction:
+ def test_append_racing_the_commit_transaction(self, db: SessionDB) -> None:
+ """An append serialized behind the commit lands AFTER it — never lost.
+
+ SQLite's write lock serializes the two transactions; whichever side
+ wins, the append must end up in the live transcript.
+ """
+ _seed(db)
+ watermark = db.get_active_message_watermark("sess1")
+
+ barrier = threading.Barrier(2, timeout=10)
+ append_err: list = []
+
+ def _racer():
+ barrier.wait()
+ try:
+ db.append_message("sess1", role="user", content="racer")
+ except Exception as exc: # pragma: no cover
+ append_err.append(exc)
+
+ t = threading.Thread(target=_racer, daemon=True)
+ t.start()
+ barrier.wait()
+ db.archive_and_compact("sess1", SUMMARY, watermark=watermark)
+ t.join(timeout=10)
+
+ assert not append_err, f"append died during commit race: {append_err}"
+ contents = [r["content"] for r in db.get_messages("sess1")]
+ assert "racer" in contents, "racing append was lost"
diff --git a/tests/test_hermes_state_compression_busy_retry.py b/tests/test_hermes_state_compression_busy_retry.py
index 5791040c400..aed45712a2f 100644
--- a/tests/test_hermes_state_compression_busy_retry.py
+++ b/tests/test_hermes_state_compression_busy_retry.py
@@ -1,27 +1,32 @@
-"""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.
+"""Appends flow freely during compression; the commit preserves them (#75316).
+
+HISTORY: ``append_message`` used to refuse while another writer held the
+session's compression lock, with a short busy-wait (#75264 → #75083). That
+fenced ordinary transcript writes behind a lease whose real job is stopping
+two COMPRESSIONS colliding — turns died as ``session_persistence_failed``
+whenever a slow provider summary overlapped an incoming message (#74568,
+#77386), and a stale lock from a dead PID blocked writes for the full TTL.
+
+CURRENT CONTRACT (watermark commit): appends never check compression_locks.
+``archive_and_compact()`` takes a watermark captured at compression start and
+re-sequences every row that arrived after it (the concurrent tail) back into
+the live transcript, atomically, instead of archiving it with the snapshot.
+The commit itself is holder-fenced: a compression whose lease was lost cannot
+publish.
"""
from __future__ import annotations
-import threading
import time
from pathlib import Path
import pytest
-from hermes_state import CompressionSessionBusyError, SessionDB
+from hermes_state import (
+ CompressionSessionBusyError,
+ SessionCompressionInProgressError,
+ SessionDB,
+)
@pytest.fixture
@@ -31,89 +36,60 @@ def db(tmp_path: Path) -> SessionDB:
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
+def test_append_is_never_blocked_by_a_foreign_compression_lock(db: SessionDB) -> None:
+ """The classic race: a steer lands while compression owns the session.
- 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.
+ Old behavior: busy-wait then land (or die on timeout). New behavior: the
+ append lands IMMEDIATELY — the watermark commit is what protects it.
"""
- 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")
+ db.append_message("sess1", role="user", content="steered mid-compression")
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"
-
+ assert elapsed < 0.5, "append must not wait on a compression lease"
+ rows = db.get_messages("sess1")
+ assert any(r["content"] == "steered mid-compression" for r in rows)
-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
+def test_append_is_never_blocked_by_a_stale_dead_pid_lock(db: SessionDB) -> None:
+ """A crashed compressor's unexpired lock must not fence writes (#74568)."""
+ assert db.try_acquire_compression_lock(
+ "sess1", "pid-9999999-long-gone", ttl_seconds=3600
+ ) is True
started = time.monotonic()
+ db.append_message("sess1", role="user", content="lands despite stale lock")
+ assert time.monotonic() - started < 0.5
+ rows = db.get_messages("sess1")
+ assert any(r["content"] == "lands despite stale lock" for r in rows)
+
+
+def test_the_lock_owner_append_still_works(db: SessionDB) -> None:
+ assert db.try_acquire_compression_lock("sess1", "compressor") is True
db.append_message(
"sess1",
role="assistant",
content="written by the compressor",
compression_lock_holder="compressor",
)
- assert time.monotonic() - started < 0.2
+ rows = db.get_messages("sess1")
+ assert any(r["content"] == "written by the compressor" for r in rows)
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
+ assert time.monotonic() - started < 0.5
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.
- """
+ """``publish_compression_child`` with a lost lease is permanent — no retry."""
started = time.monotonic()
with pytest.raises(CompressionSessionBusyError):
db.publish_compression_child(