The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): the first turn on a new session id takes the turn lease too
John Paul Soliva057bbb3fb903
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.pyindex 520c443c4da..673eb8ead63 100644--- a/agent/turn_facade_lease.py+++ b/agent/turn_facade_lease.py@@ -239,7 +239,7 @@ def admit_durable_turn_lease(agent, *, session_id: str, relay_turn_id: str, task_context: Dict[str, Any],conversation_history: Optional[List[Dict[str, Any]]],) -> TurnLeaseAdmission:- """Acquire the session turn lease when the session is durable; build (not start) its threads.+ """Acquire the session turn lease (the row need not exist yet); build (not start) its threads.Mutates ``task_context["session_id"]`` and ``agent.session_id`` when the wait forced a resume-idreload. Returns an ``early_result`` (interrupted / timed out) instead of a lease when admission@@ -248,17 +248,20 @@ def admit_durable_turn_lease(admission = TurnLeaseAdmission(conversation_history=conversation_history)if db is None or not session_id:return admission- # A fresh session id has no durable transcript to race over, and callers may supply an- # in-memory seed before the row exists — reloading would erase it. Check the concrete type:- # MagicMock-style shims accept any attribute without the protocol.+ # Check the concrete type: MagicMock-style shims accept any attribute without the protocol.if (getattr(agent, "_persist_disabled", False)- or not _durable_session_exists(db, session_id)or not callable(getattr(type(db), "acquire_session_turn_lease", None))):return admission- # Row proven to exist — suppress the redundant create attempt.- agent._session_db_created = True+ # A session id without a row still takes the lease: client-addressed ids (API server+ # X-Hermes-Session-Id, /v1/runs session_id, fingerprint-derived chat ids) are not+ # process-unique, and the first turn creates the row mid-turn, so a second writer would+ # otherwise find the row, take an unheld lease and interleave its turn into this one.+ durable = _durable_session_exists(db, session_id)+ if durable:+ # Row proven to exist — suppress the redundant create attempt.+ agent._session_db_created = Trueholder = (f"pid={os.getpid()}:turn={relay_turn_id}:platform={task_context['platform'] or 'unknown'}")@@ -287,7 +290,9 @@ def admit_durable_turn_lease(agent._active_session_turn_lease_holder = holderagent._active_session_turn_lease_ttl_seconds = LEASE_TTL_SECONDStry:- if waited:+ # Reload only a transcript that exists: callers may seed a fresh id in memory before its+ # row is written, and reloading an absent row would erase that seed.+ if waited and (durable or _durable_session_exists(db, session_id)):agent._emit_status("Session is free; loading the latest transcript...")# The holder may have compressed/rotated the session while we waited: reload only# AFTER admission; an immediate acquisition skips this (needless prompt-cache miss).diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.pyindex 017c5c90250..6e62e8d9e29 100644--- a/tests/agent/test_cross_process_turn_lease.py+++ b/tests/agent/test_cross_process_turn_lease.py@@ -170,8 +170,16 @@ def test_run_conversation_acquires_lease_when_session_probe_raises(monkeypatch):]-def test_fresh_session_keeps_caller_seed_without_durable_lease(monkeypatch):+def test_fresh_session_keeps_caller_seed(monkeypatch):+ """Even after a contended wait, a session with no row keeps the in-memory seed."""db = _DB(session_exists=False)++ def acquire_with_wait(session_id, holder, **kwargs):+ db.events.append(("acquire", session_id, holder))+ kwargs["on_wait"](0.0)+ return True++ db.acquire_session_turn_lease = acquire_with_waitagent = _agent_with_db(db, session_id="fresh", platform="subagent")agent._session_db_created = Falseagent._parent_session_id = "parent"@@ -189,7 +197,54 @@ def test_fresh_session_keeps_caller_seed_without_durable_lease(monkeypatch):AIAgent.run_conversation(agent, "work", conversation_history=seed)assert observed["history"] is seed- assert db.events == []+ assert "reload" not in [event[0] for event in db.events]+++def test_first_turn_on_fresh_session_serializes_a_second_writer(tmp_path, monkeypatch):+ """A client-addressed session id has no row until its first turn writes one; a second+ turn arriving meanwhile must wait for that turn and see its rows, not interleave."""+ path = tmp_path / "state.db"+ db_a, db_b = SessionDB(path), SessionDB(path)+ a_in_turn, a_may_finish, a_finished = threading.Event(), threading.Event(), threading.Event()+ observed = {}++ def fake_run(_agent, message, _system, history, *_args, **_kwargs):+ if message == "first":+ _agent._session_db.create_session("client-id", source="api_server")+ _agent._session_db.append_message("client-id", "user", "first")+ a_in_turn.set()+ a_may_finish.wait(timeout=10)+ _agent._session_db.append_message("client-id", "assistant", "first answer")+ else:+ observed["a_finished"] = a_finished.is_set()+ observed["history"] = [m.get("content") for m in history]+ return {"final_response": "ok", "messages": history, "failed": False}++ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)+ agent_a = _agent_with_db(db_a, session_id="client-id", platform="api_server")+ agent_a._session_db_created = False++ def run_a():+ AIAgent.run_conversation(agent_a, "first", conversation_history=[])+ a_finished.set()++ thread_a = threading.Thread(target=run_a)+ thread_a.start()+ assert a_in_turn.wait(timeout=10)+ agent_b = _agent_with_db(db_b, session_id="client-id", platform="api_server")+ thread_b = threading.Thread(+ target=lambda: AIAgent.run_conversation(+ agent_b, "second", conversation_history=db_b.get_messages_as_conversation("client-id")))+ thread_b.start()+ time.sleep(0.5)+ a_may_finish.set()+ thread_a.join(timeout=10)+ thread_b.join(timeout=10)++ assert observed["a_finished"] is True+ assert observed["history"] == ["first", "first answer"]+ db_a.close()+ db_b.close()def test_run_conversation_lease_timeout_returns_resend_notice(monkeypatch):diff --git a/tests/agent/test_turn_facade_lease.py b/tests/agent/test_turn_facade_lease.pyindex 85dba7cdbae..29df52d2c3a 100644--- a/tests/agent/test_turn_facade_lease.py+++ b/tests/agent/test_turn_facade_lease.py@@ -59,11 +59,17 @@ def _admit(agent, history=None):)-def test_no_lease_without_durable_row_or_when_persist_disabled():+def test_fresh_row_leases_with_seed_kept_and_persist_disabled_skips(monkeypatch):+ monkeypatch.setattr(+ "agent.turn_liveness.resolve_turn_liveness_settings", lambda cfg: (None, 1.0)+ )seed = [{"role": "user", "content": "hi"}]- admission = _admit(_agent(_Db(exists=False)), seed)- assert admission.lease is None and admission.early_result is None+ agent = _agent(_Db(exists=False))+ admission = _admit(agent, seed)+ assert admission.lease is not None and admission.early_result is Noneassert admission.conversation_history is seed+ assert getattr(agent, "_session_db_created", False) is False+ admission.lease.release()db = _Db()admission = _admit(_agent(db, _persist_disabled=True), seed)