The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): an unreadable session row is unknown, not existing
John Paul Solivad9b456ed0037
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.pyindex 047d7b3187e..882874d41d3 100644--- a/agent/turn_facade_lease.py+++ b/agent/turn_facade_lease.py@@ -218,18 +218,18 @@ class TurnLeaseAdmission:conversation_history: Optional[List[Dict[str, Any]]] = None-def _durable_session_exists(db, session_id: str) -> bool:+def _durable_session_exists(db, session_id: str) -> Optional[bool]:+ """True / False when the row read answered; None when it failed and the state is unknown."""try:return db.get_session(session_id) is not Noneexcept Exception:- # A locked / non-WAL read is not proof the row is absent: get_session returns None — it- # does not raise — when the row is missing. Treat the session as durable so a waited turn- # reloads rather than runs on a stale in-memory transcript. See #84234.+ # A locked / non-WAL read proves neither presence nor absence: get_session returns None —+ # it does not raise — when the row is missing. See #84234.logger.warning(- "Could not check durable session after turn lease admission; treating it as durable",+ "Could not check durable session after turn lease admission; row state is unknown",exc_info=True,)- return True+ return Nonedef admit_durable_turn_lease(@@ -288,11 +288,13 @@ def admit_durable_turn_lease(durable = _durable_session_exists(db, session_id)if durable:# Row proven to exist — suppress the redundant create attempt. A missing row leaves- # the flag alone: the flush heals a row deleted under a live agent (#123583).+ # the flag alone: the flush heals a row deleted under a live agent (#123583). So does+ # an unknown one: the create is an upsert that never overwrites an existing row.agent._session_db_created = True# 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:+ # row is written, and reloading an absent row would erase that seed. An unknown row still+ # reloads after a wait (the holder wrote meanwhile); that read raising ends the turn.+ if waited and durable is not False: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).@@ -311,7 +313,8 @@ def admit_durable_turn_lease(if isinstance(m, dict) and m.get(_PERSIST_AFTER_ADMISSION_INTERRUPT)and "_row_id" not in m)- admission.conversation_history = reloaded+ if durable or reloaded:+ admission.conversation_history = reloadedlease.build_threads()except BaseException:# The façade never saw this lease; release here so an admitted row is not leaked.diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.pyindex 55f1cac95ea..c08c185767c 100644--- a/tests/agent/test_cross_process_turn_lease.py+++ b/tests/agent/test_cross_process_turn_lease.py@@ -242,6 +242,51 @@ def test_row_deleted_during_the_wait_keeps_the_caller_history(monkeypatch):assert observed["history"] is seed+def _run_with_unreadable_row(monkeypatch, *, waited):+ """Run one turn whose session row read fails after the lease is admitted."""+ db = _DB()++ def locked_get_session(_session_id):+ raise sqlite3.OperationalError("database is locked")++ def acquire(session_id, holder, **kwargs):+ db.events.append(("acquire", session_id, holder))+ if waited:+ kwargs["on_wait"](0.0)+ return True++ db.get_session = locked_get_session+ db.acquire_session_turn_lease = acquire+ db.get_messages_as_conversation = lambda *_a, **_k: []+ agent = _agent_with_db(db, session_id="client-id", platform="api_server")+ agent._session_db_created = False+ observed = {}++ def fake_run(_agent, _message, _system, history, *_args, **_kwargs):+ observed["history"] = history+ observed["row_known"] = _agent._session_db_created+ return {"final_response": "ok", "messages": history, "failed": False}++ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)+ seed = [{"role": "user", "content": "caller history"}]+ AIAgent.run_conversation(agent, "work", conversation_history=seed)+ return observed, seed+++def test_unreadable_row_is_not_recorded_as_existing(monkeypatch):+ """A failed read proves nothing, so the row create (an upsert) must still be attempted."""+ observed, seed = _run_with_unreadable_row(monkeypatch, waited=False)++ assert observed["row_known"] is False+ assert observed["history"] is seed+++def test_unreadable_row_with_nothing_to_reload_keeps_the_caller_history(monkeypatch):+ observed, seed = _run_with_unreadable_row(monkeypatch, waited=True)++ assert observed["history"] is seed++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 secondturn arriving meanwhile must wait for that turn and see its rows, not interleave."""