The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): serialize turns across processes
fangliquan6e929a96946a
diff --git a/hermes_state.py b/hermes_state.pyindex 1b4fad10d01..8b33c6cdd06 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1492,7 +1492,7 @@ def is_disk_full_error(exc: BaseException | str | None) -> bool:# enumerate causes (e.g. the cron scheduler's explainer-variant suppression)# must iterate this tuple instead of hardcoding the list, so adding a bucket# can never silently desynchronize them.-PERSISTENCE_ERROR_CAUSES = ("locked", "disk", "unknown")+PERSISTENCE_ERROR_CAUSES = ("locked", "compression", "disk", "unknown")def classify_persistence_error(exc_or_str) -> str:@@ -1505,9 +1505,10 @@ def classify_persistence_error(exc_or_str) -> str:send it again", while a full disk or read-only database needs thedisk-space/permissions advice. Returns one of PERSISTENCE_ERROR_CAUSES:- * ``"locked"`` — lock/busy contention (another process holds the write- lock, or a live compression lease refused the write); transient,- retry-later guidance applies.+ * ``"locked"`` — SQLite lock/busy contention (another process holds the+ database write lock); transient, retry-later guidance applies.+ * ``"compression"`` — a live compression lease refused the transcript+ write; the database itself is healthy and unlocked.* ``"disk"`` — disk full / read-only / permission-shaped failures(delegates the disk-full patterns to :func:`is_disk_full_error` so thetwo classifiers can never drift apart — e.g. ENOSPC).@@ -1521,13 +1522,13 @@ def classify_persistence_error(exc_or_str) -> str:# "busy", so it must be matched by type and by phrase (for strings that# survived RPC wrapping).if isinstance(exc_or_str, CompressionSessionBusyError):- return "locked"+ return "compression"text = str(exc_or_str).lower()+ if "being compressed" in text or "compression lease" in text:+ return "compression"if ("locked" in textor "busy" in text- or "being compressed" in text- or "compression lease" in text):return "locked"if (@@ -5739,6 +5740,136 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)session_id, exc,)+ def _session_turn_lease_key(self, session_id: str) -> str:+ """Return the stable serialization key for every compression segment."""+ if not session_id:+ return session_id+ try:+ current = self.get_session(session_id)+ seen = {session_id}+ while current and self._is_compression_child_row(current):+ parent_id = current.get("parent_session_id")+ if not parent_id or parent_id in seen:+ break+ parent = self.get_session(parent_id)+ if not parent:+ break+ seen.add(parent_id)+ current = parent+ return str(current.get("id") or session_id) if current else session_id+ except Exception:+ return session_id++ def try_acquire_session_turn_lease(+ self,+ session_id: str,+ holder: str,+ *,+ ttl_seconds: float = 300.0,+ ) -> bool:+ """Atomically acquire the cross-process turn lease for a conversation.++ Compression rotates a session into child segments, so the durable key+ is the lineage root rather than the current segment id. Expired leases+ and leases whose structured local holder PID is known dead are reclaimed+ in the same write transaction as acquisition.+ """+ if not session_id or not holder:+ return False+ conversation_id = self._session_turn_lease_key(session_id)+ now = time.time()+ expires_at = now + max(0.1, float(ttl_seconds))++ def _do(conn):+ row = conn.execute(+ "SELECT holder, expires_at FROM session_turn_leases "+ "WHERE conversation_id = ?",+ (conversation_id,),+ ).fetchone()+ if row is not None:+ current_holder = row["holder"]+ if (+ float(row["expires_at"]) <= now+ or _compression_lock_holder_process_is_dead(current_holder)+ ):+ conn.execute(+ "DELETE FROM session_turn_leases "+ "WHERE conversation_id = ? AND holder = ?",+ (conversation_id, current_holder),+ )+ conn.execute(+ "INSERT OR IGNORE INTO session_turn_leases "+ "(conversation_id, holder, acquired_at, expires_at) "+ "VALUES (?, ?, ?, ?)",+ (conversation_id, holder, now, expires_at),+ )+ owner = conn.execute(+ "SELECT holder FROM session_turn_leases WHERE conversation_id = ?",+ (conversation_id,),+ ).fetchone()+ return owner is not None and owner["holder"] == holder++ return bool(self._execute_write(_do))++ def acquire_session_turn_lease(+ self,+ session_id: str,+ holder: str,+ *,+ ttl_seconds: float = 300.0,+ wait_seconds: float = 1800.0,+ poll_interval_seconds: float = 0.1,+ ) -> bool:+ """Wait for a cross-process turn lease without holding a SQLite lock."""+ deadline = time.monotonic() + max(0.0, float(wait_seconds))+ while True:+ if self.try_acquire_session_turn_lease(+ session_id, holder, ttl_seconds=ttl_seconds+ ):+ return True+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return False+ time.sleep(min(max(0.01, float(poll_interval_seconds)), remaining))++ def refresh_session_turn_lease(+ self,+ session_id: str,+ holder: str,+ *,+ ttl_seconds: float = 300.0,+ ) -> bool:+ """Extend a turn lease only while ``holder`` still owns it."""+ if not session_id or not holder:+ return False+ conversation_id = self._session_turn_lease_key(session_id)+ expires_at = time.time() + max(0.1, float(ttl_seconds))++ def _do(conn):+ cursor = conn.execute(+ "UPDATE session_turn_leases SET expires_at = ? "+ "WHERE conversation_id = ? AND holder = ?",+ (expires_at, conversation_id, holder),+ )+ return cursor.rowcount > 0++ return bool(self._execute_write(_do))++ def release_session_turn_lease(self, session_id: str, holder: str) -> None:+ """Release a turn lease iff ``holder`` still owns it; idempotent."""+ if not session_id or not holder:+ return+ conversation_id = self._session_turn_lease_key(session_id)++ def _do(conn):+ conn.execute(+ "DELETE FROM session_turn_leases "+ "WHERE conversation_id = ? AND holder = ?",+ (conversation_id, holder),+ )++ self._execute_write(_do)+def get_compression_lock_holder(self, session_id: str) -> Optional[str]:"""Return the current (non-expired) holder for ``session_id``, or None.diff --git a/hermes_state_common.py b/hermes_state_common.pyindex a6f29dbe75a..28f3a63cdbe 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -383,6 +383,13 @@ CREATE TABLE IF NOT EXISTS compression_locks (expires_at REAL NOT NULL);+CREATE TABLE IF NOT EXISTS session_turn_leases (+ conversation_id TEXT PRIMARY KEY,+ holder TEXT NOT NULL,+ acquired_at REAL NOT NULL,+ expires_at REAL NOT NULL+);+CREATE TABLE IF NOT EXISTS async_delegations (delegation_id TEXT PRIMARY KEY,origin_session TEXT NOT NULL,@@ -419,6 +426,7 @@ CREATE INDEX IF NOT EXISTS idx_messages_assistant_calls_by_sessionON messages(session_id)WHERE role = 'assistant' AND tool_calls IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_compression_locks_expires ON compression_locks(expires_at);+CREATE INDEX IF NOT EXISTS idx_session_turn_leases_expires ON session_turn_leases(expires_at);CREATE INDEX IF NOT EXISTS idx_session_model_usage_session ON session_model_usage(session_id);CREATE INDEX IF NOT EXISTS idx_session_model_usage_model ON session_model_usage(model);CREATE INDEX IF NOT EXISTS idx_async_delegations_deliverydiff --git a/run_agent.py b/run_agent.pyindex 12e7da647eb..46bf45f3bf3 100644--- a/run_agent.py+++ b/run_agent.py@@ -3722,6 +3722,13 @@ class AIAgent:)if reason == "session_persistence_failed":cause = persistence_cause or "unknown"+ if cause == "compression":+ return (+ prefix+ + "the turn was stopped because another process was "+ "compressing this session. Your message should already be "+ "saved — please send it again after compression completes."+ )if cause == "locked":return (prefix@@ -8061,12 +8068,108 @@ class AIAgent:)relay_lease = Nonerelay_turn = None+ durable_turn_lease = None+ durable_turn_lease_stop = None+ durable_turn_lease_thread = Nonetoken = Noneacct_token = Nonetask_started = Falsetask_finished = Falserelay_outcome = "failed"try:+ # Serialize the full load -> run -> flush region across Hermes+ # processes. Gateway's asyncio lease closes alias routing inside one+ # process; this durable lease covers Desktop, CLI resume, gateway,+ # and background delivery processes sharing state.db (#84234).+ _turn_db = getattr(self, "_session_db", None)+ _durable_session_exists = False+ if _turn_db is not None and session_id:+ try:+ _durable_session_exists = _turn_db.get_session(session_id) is not None+ except Exception:+ logger.debug(+ "Could not check durable session before turn lease",+ exc_info=True,+ )+ if (+ _turn_db is not None+ and session_id+ and not getattr(self, "_persist_disabled", False)+ # A fresh session id is process-unique and has no durable+ # transcript to race over. More importantly, subagent/new-turn+ # callers may intentionally supply an in-memory seed before the+ # row exists; reloading an absent row would erase that seed.+ and _durable_session_exists+ # Test doubles and third-party DB shims may accept arbitrary+ # MagicMock attributes without implementing the protocol. Check+ # the concrete type so only real implementations opt in.+ and callable(+ getattr(type(_turn_db), "acquire_session_turn_lease", None)+ )+ ):+ # Resumed agents also defer their create check until the turn+ # prologue. We just proved this row exists, so suppress the+ # redundant create attempt after acquiring it.+ self._session_db_created = True+ durable_turn_lease = (+ f"pid={os.getpid()}:turn={relay_turn_id}:platform="+ f"{task_context['platform'] or 'unknown'}"+ )+ _lease_ttl = 300.0+ if not _turn_db.acquire_session_turn_lease(+ session_id,+ durable_turn_lease,+ ttl_seconds=_lease_ttl,+ wait_seconds=1800.0,+ ):+ raise TimeoutError(+ f"session turn lease wait timed out for {session_id}"+ )++ # The holder may have compressed and rotated the session while+ # this process waited. Resolve and reload only AFTER admission;+ # a caller-provided in-memory snapshot is necessarily stale.+ latest_session_id = _turn_db.resolve_resume_session_id(session_id)+ if latest_session_id:+ self.session_id = latest_session_id+ task_context["session_id"] = latest_session_id+ conversation_history = _turn_db.get_messages_as_conversation(+ self.session_id,+ repair_alternation=True,+ )++ # Long model/tool/compression turns outlive a fixed TTL. Refresh+ # in a daemon thread; holder-qualified UPDATE and DELETE fence a+ # late refresher/release from a successor lease.+ durable_turn_lease_stop = threading.Event()++ def _refresh_durable_turn_lease() -> None:+ while not durable_turn_lease_stop.wait(60.0):+ try:+ if not _turn_db.refresh_session_turn_lease(+ session_id,+ durable_turn_lease,+ ttl_seconds=_lease_ttl,+ ):+ logger.error(+ "Lost session turn lease while turn is active: %s",+ session_id,+ )+ return+ except Exception:+ logger.warning(+ "Failed to refresh session turn lease: %s",+ session_id,+ exc_info=True,+ )++ durable_turn_lease_thread = threading.Thread(+ target=_refresh_durable_turn_lease,+ name="session-turn-lease-refresh",+ daemon=True,+ )+ durable_turn_lease_thread.start()+relay_lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(profile_key=relay_runtime.current_profile_key(),session_id=task_context["session_id"],@@ -8166,6 +8269,24 @@ class AIAgent:relay_lease)finally:+ if durable_turn_lease_stop is not None:+ durable_turn_lease_stop.set()+ if (+ durable_turn_lease_thread is not None+ and durable_turn_lease_thread.is_alive()+ ):+ durable_turn_lease_thread.join(timeout=1.0)+ if durable_turn_lease is not None:+ try:+ _turn_db.release_session_turn_lease(+ session_id, durable_turn_lease+ )+ except Exception:+ logger.error(+ "Failed to release session turn lease: %s",+ session_id,+ exc_info=True,+ )# Always clear mid-turn labels when the turn exits — including# interrupted early returns that skip finalize_turn. Keep ts.try:diff --git a/tests/run_agent/test_cross_process_turn_lease.py b/tests/run_agent/test_cross_process_turn_lease.pynew file mode 100644index 00000000000..1296f6d2a18--- /dev/null+++ b/tests/run_agent/test_cross_process_turn_lease.py@@ -0,0 +1,102 @@+"""AIAgent enters turns only after acquiring and reloading durable state."""++from __future__ import annotations++from run_agent import AIAgent+++class _DB:+ def __init__(self, session_exists=True):+ self.events = []+ self.session_exists = session_exists++ def get_session(self, session_id):+ return {"id": session_id} if self.session_exists else None++ def acquire_session_turn_lease(self, session_id, holder, **kwargs):+ self.events.append(("acquire", session_id, holder))+ return True++ def resolve_resume_session_id(self, session_id):+ self.events.append(("resolve", session_id))+ return "compressed-tip"++ def get_messages_as_conversation(self, session_id, **kwargs):+ self.events.append(("reload", session_id, kwargs))+ return [{"role": "user", "content": "durable latest"}]++ def refresh_session_turn_lease(self, session_id, holder, **kwargs):+ return True++ def release_session_turn_lease(self, session_id, holder):+ self.events.append(("release", session_id, holder))+++def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):+ db = _DB()+ agent = AIAgent.__new__(AIAgent)+ agent.session_id = "stale-parent"+ agent.platform = "desktop"+ agent.model = "test-model"+ agent._session_db = db+ agent._session_db_created = True+ agent._persist_disabled = False+ agent._parent_session_id = None+ agent._relay_pending_turn_id = None+ agent._reset_activity_labels_after_turn = lambda: None+ agent._conversation_root_id = lambda: "stale-parent"++ observed = {}++ def fake_run(_agent, _message, _system, history, *_args, **_kwargs):+ observed["history"] = history+ observed["session_id"] = _agent.session_id+ return {"final_response": "ok", "messages": history, "failed": False}++ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)+ result = AIAgent.run_conversation(+ agent,+ "new message",+ conversation_history=[{"role": "user", "content": "stale"}],+ )++ assert result["final_response"] == "ok"+ assert observed == {+ "history": [{"role": "user", "content": "durable latest"}],+ "session_id": "compressed-tip",+ }+ assert [event[0] for event in db.events] == [+ "acquire",+ "resolve",+ "reload",+ "release",+ ]+++def test_fresh_session_keeps_caller_seed_without_durable_lease(monkeypatch):+ db = _DB(session_exists=False)+ agent = AIAgent.__new__(AIAgent)+ agent.session_id = "fresh"+ agent.platform = "subagent"+ agent.model = "test-model"+ agent._session_db = db+ agent._session_db_created = False+ agent._persist_disabled = False+ agent._parent_session_id = "parent"+ agent._relay_pending_turn_id = None+ agent._reset_activity_labels_after_turn = lambda: None+ agent._conversation_root_id = lambda: "parent"++ observed = {}++ def fake_run(_agent, _message, _system, history, *_args, **_kwargs):+ observed["history"] = history+ return {"final_response": "ok", "messages": history, "failed": False}++ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)+ seed = [{"role": "user", "content": "delegated context"}]++ AIAgent.run_conversation(agent, "work", conversation_history=seed)++ assert observed["history"] is seed+ assert db.events == []\ No newline at end of filediff --git a/tests/run_agent/test_turn_completion_explainer.py b/tests/run_agent/test_turn_completion_explainer.pyindex 5b67f099b21..533e4dfd3ef 100644--- a/tests/run_agent/test_turn_completion_explainer.py+++ b/tests/run_agent/test_turn_completion_explainer.py@@ -109,6 +109,16 @@ def test_explanation_persistence_locked_cause_says_busy_not_disk():assert "permission" not in lower+def test_explanation_persistence_compression_cause_is_specific():+ out = AIAgent._format_turn_completion_explanation(+ "session_persistence_failed", "compression"+ )+ lower = out.lower()+ assert "compression" in lower+ assert "database" not in lower+ assert "disk" not in lower++def test_explanation_persistence_disk_cause_keeps_disk_wording():out = AIAgent._format_turn_completion_explanation("session_persistence_failed", "disk"@@ -194,7 +204,7 @@ def test_classify_persistence_error_reuses_disk_full_markers():) == "disk"-def test_classify_persistence_error_compression_busy_is_locked():+def test_classify_persistence_error_compression_busy_is_distinct():"""A live compression lease refusing the write is contention, notstorage damage — but its message contains neither 'locked' nor 'busy',so it must classify by exception type (and by phrase for RPC-wrapped@@ -209,17 +219,17 @@ def test_classify_persistence_error_compression_busy_is_locked():SessionCompressionInProgressError("Session 'abc' is being compressed by another writer")- ) == "locked"+ ) == "compression"assert classify_persistence_error(CompressionSessionBusyError("Compression lease lost before publication: abc")- ) == "locked"+ ) == "compression"# RPC-wrapped string forms (exception type lost in transit).assert classify_persistence_error("Session 'abc' is being compressed by another writer"- ) == "locked"+ ) == "compression"assert classify_persistence_error("Compression lease lost before publication: abc"- ) == "locked"+ ) == "compression"def test_persistence_error_causes_tuple_matches_classifier():@@ -229,6 +239,7 @@ def test_persistence_error_causes_tuple_matches_classifier():probes = ("database is locked",+ "Session 'abc' is being compressed by another writer","database or disk is full","something else entirely",None,diff --git a/tests/state/test_session_turn_lease.py b/tests/state/test_session_turn_lease.pynew file mode 100644index 00000000000..b177576fa58--- /dev/null+++ b/tests/state/test_session_turn_lease.py@@ -0,0 +1,128 @@+"""Cross-process session turn lease behavior (#84234)."""++from __future__ import annotations++import os+import threading+import time++from hermes_state import SessionDB+++def test_turn_lease_serializes_separate_session_db_instances(tmp_path):+ """A second process-shaped DB handle waits for the current turn owner."""+ path = tmp_path / "state.db"+ first = SessionDB(path)+ second = SessionDB(path)+ first.create_session("shared", source="test")++ first_holder = f"pid={os.getpid()}:turn=first"+ second_holder = f"pid={os.getpid()}:turn=second"+ assert first.try_acquire_session_turn_lease(+ "shared", first_holder, ttl_seconds=5+ )++ released = threading.Event()++ def release_first():+ time.sleep(0.2)+ first.release_session_turn_lease("shared", first_holder)+ released.set()++ thread = threading.Thread(target=release_first, daemon=True)+ thread.start()+ started = time.monotonic()+ try:+ assert second.acquire_session_turn_lease(+ "shared",+ second_holder,+ ttl_seconds=5,+ wait_seconds=2,+ poll_interval_seconds=0.02,+ )+ finally:+ thread.join(timeout=2)++ assert released.is_set()+ assert time.monotonic() - started >= 0.15+ second.release_session_turn_lease("shared", second_holder)+++def test_turn_lease_is_scoped_to_conversation_root(tmp_path):+ """Compression descendants share one durable serialization domain."""+ db = SessionDB(tmp_path / "state.db")+ db.create_session("root", source="test")+ db.end_session("root", "compression")+ db.create_session("child", source="test", parent_session_id="root")++ root_holder = f"pid={os.getpid()}:turn=root"+ child_holder = f"pid={os.getpid()}:turn=child"+ assert db.try_acquire_session_turn_lease(+ "root", root_holder, ttl_seconds=5+ )+ assert not db.try_acquire_session_turn_lease(+ "child", child_holder, ttl_seconds=5+ )+ db.release_session_turn_lease("child", root_holder)+++def test_turn_lease_does_not_serialize_delegate_child_with_parent(tmp_path):+ """Only compression continuation segments share a conversation lease."""+ db = SessionDB(tmp_path / "state.db")+ db.create_session("parent", source="test")+ db.create_session(+ "delegate",+ source="delegate",+ parent_session_id="parent",+ model_config={"_delegate_from": "parent"},+ )++ parent_holder = f"pid={os.getpid()}:turn=parent"+ delegate_holder = f"pid={os.getpid()}:turn=delegate"+ assert db.try_acquire_session_turn_lease(+ "parent", parent_holder, ttl_seconds=5+ )+ assert db.try_acquire_session_turn_lease(+ "delegate", delegate_holder, ttl_seconds=5+ )+++def test_turn_lease_refresh_and_release_are_owner_fenced(tmp_path):+ db = SessionDB(tmp_path / "state.db")+ db.create_session("shared", source="test")++ current_holder = f"pid={os.getpid()}:turn=current"+ stale_holder = f"pid={os.getpid()}:turn=stale"+ next_holder = f"pid={os.getpid()}:turn=next"+ assert db.try_acquire_session_turn_lease(+ "shared", current_holder, ttl_seconds=5+ )+ assert not db.refresh_session_turn_lease(+ "shared", stale_holder, ttl_seconds=5+ )+ db.release_session_turn_lease("shared", stale_holder)+ assert not db.try_acquire_session_turn_lease(+ "shared", next_holder, ttl_seconds=5+ )++ assert db.refresh_session_turn_lease(+ "shared", current_holder, ttl_seconds=5+ )+ db.release_session_turn_lease("shared", current_holder)+ assert db.try_acquire_session_turn_lease(+ "shared", next_holder, ttl_seconds=5+ )+++def test_expired_turn_lease_is_reclaimed(tmp_path):+ db = SessionDB(tmp_path / "state.db")+ db.create_session("shared", source="test")+ assert db.try_acquire_session_turn_lease(+ "shared", "legacy-holder", ttl_seconds=0.05+ )++ time.sleep(0.15)++ assert db.try_acquire_session_turn_lease(+ "shared", "pid=202:turn=reclaimer", ttl_seconds=5+ )\ No newline at end of file