The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): harden the off-turn session-key fixes from a parallel review (#123545)
Halldrixac0b07597d76
diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex f81d9929db3..7764b29da6c 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -38,8 +38,11 @@ ABSORBED_MESSAGE_UIDS = "_absorbed_message_uids"TOOL_CALL_UIDS = "_tool_call_uids"TOOL_CALL_UID = "_tool_call_uid"PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(- {"timestamp", "display_kind", "display_metadata", "_row_id", MERGED_TURN_PREFIX, MESSAGE_UID,- ABSORBED_MESSAGE_UIDS, TOOL_CALL_UIDS, TOOL_CALL_UID}+ # Membership is the real contract, NOT the leading underscore: the chat-completions transport happens+ # to sweep underscore keys, but turn_context.py pops this set from every outgoing copy and a strict+ # backend 400s on any key it does not know.+ {"timestamp", "display_kind", "display_metadata", "_row_id", "_submit_row_session_id",+ MERGED_TURN_PREFIX, MESSAGE_UID, ABSORBED_MESSAGE_UIDS, TOOL_CALL_UIDS, TOOL_CALL_UID}) | REPAIR_BOOKKEEPING_FIELDSdiff --git a/tests/tui_gateway/test_submit_row_session_target.py b/tests/tui_gateway/test_submit_row_session_target.pyindex b7a476c5771..ae32b6ea77a 100644--- a/tests/tui_gateway/test_submit_row_session_target.py+++ b/tests/tui_gateway/test_submit_row_session_target.py@@ -68,6 +68,20 @@ def _rows(db, key):db.get_messages_as_conversation(key, include_inactive=True)]+def _rotated_session(monkeypatch, db):+ """A live desktop session whose agent already rotated onto a continuation while ``session_key``+ still names the (reopened) parent — the state every turn after a compression rotation sees."""+ sid, key = _desktop_session(monkeypatch, db)+ session = server._sessions[sid]+ with session["history_lock"]:+ session["running"] = True+ server._start_inflight_turn(session, "earlier turn")+ assert server._ensure_session_db_row(session) is not False+ agent = _flush_agent(db, key)+ session["agent"] = agent+ return sid, key, session, agent, _rotate_to_compression_child(db, key, agent, reopen_parent=True)++def test_submit_user_row_lands_where_the_turns_tool_rows_land(monkeypatch, tmp_path):"""The reporter's exact shape: one typed message, a tool result and the final text — all one session."""db = SessionDB(db_path=tmp_path / "state.db")@@ -147,6 +161,10 @@ def test_expanded_submit_row_is_rewritten_on_the_session_that_owns_it(monkeypatcdb.close()+def _full_rows(db, key):+ return [(r["role"], str(r["content"])) for r in db.get_messages_as_conversation(key, include_inactive=True)]++def test_model_switch_marker_lands_in_the_live_session(monkeypatch, tmp_path):"""``_append_model_switch_marker`` writes a DURABLE ``role=user`` pivot under ``session_key`` while thelive agent writes to ``agent.session_id``. On a rotated session the notice is filed under a parent the@@ -156,12 +174,10 @@ def test_model_switch_marker_lands_in_the_live_session(monkeypatch, tmp_path):sid, key, session, agent, child = _rotated_session(monkeypatch, db)try:server._append_model_switch_marker(session, model="test-model-2", provider="test-provider")- full = lambda k: [(r["role"], str(r["content"])) for r in # noqa: E731- db.get_messages_as_conversation(k, include_inactive=True)]prefix = server._MODEL_SWITCH_MARKER_PREFIX- assert [r for r in full(child) if prefix in r[1]], f"marker not in the live session: {full(child)}"- assert not [r for r in full(key) if prefix in r[1]], (- f"marker filed under the rotated-away parent: {full(key)}")+ assert [r for r in _full_rows(db, child) if prefix in r[1]], f"marker not in the live session: {_full_rows(db, child)}"+ assert not [r for r in _full_rows(db, key) if prefix in r[1]], (+ f"marker filed under the rotated-away parent: {_full_rows(db, key)}")finally:server._sessions.pop(sid, None)db.close()@@ -248,18 +264,6 @@ def test_unrotated_session_keeps_writing_to_session_key(monkeypatch, tmp_path):db.close()-def _rotated_session(monkeypatch, db):- """A live desktop session whose agent already rotated onto a continuation while ``session_key``- still names the (reopened) parent — the state every turn after a compression rotation sees."""- sid, key = _desktop_session(monkeypatch, db)- session = server._sessions[sid]- with session["history_lock"]:- session["running"] = True- server._start_inflight_turn(session, "earlier turn")- assert server._ensure_session_db_row(session) is not False- agent = _flush_agent(db, key)- session["agent"] = agent- return sid, key, session, agent, _rotate_to_compression_child(db, key, agent, reopen_parent=True)def test_busy_queue_accept_row_lands_with_the_turn_and_is_addressed_there(monkeypatch, tmp_path):diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 517c389e7ac..eb75fb0ab5b 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1816,7 +1816,11 @@ def _append_model_switch_marker(session: dict | None, *, model: str, provider: smessage_uid=stamp_message_uid(entry))entry[_DB_PERSISTED_MARKER] = Trueexcept Exception:- logger.debug("failed to persist model switch marker", exc_info=True)+ # warning, not debug: filing the pivot in the LIVE session (#123545) means this write can now hit+ # CompressionSessionClosedError on a closed parent, which the old session_key target could not.+ # Swallowed at debug, a model switch silently loses its durable notice — the next resume replays+ # without it and nothing lands in errors.log. Matches _persist_live_session_system_prompt above.+ logger.warning("failed to persist model switch marker", exc_info=True)def _write_config_key(key_path: str, value):diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 68e1c88e533..beb645f4ba1 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -564,13 +564,12 @@ def _submit_row_target_key(session: dict) -> str:_SUBMIT_ROW_SESSION_KEY = "_submit_row_session_id"-def _submit_row_owner_key(staged: Any, session: dict) -> str:- """The session id a staged submit row lives under: recorded at write time, else the current best."""- if isinstance(staged, dict):- recorded = str(staged.get(_SUBMIT_ROW_SESSION_KEY) or "")- if recorded:- return recorded- return _submit_row_target_key(session)+def _submit_row_owner_key(staged: dict, session: dict) -> str:+ """The session id a staged submit row lives under: recorded at write time, else the current best.+ Every caller narrows to a dict (and checks ``_row_id``) immediately before, so the recorded value is+ the answer whenever the row exists; the re-derivation only covers a dict that predates the stamp."""+ recorded = str(staged.get(_SUBMIT_ROW_SESSION_KEY) or "")+ return recorded or _submit_row_target_key(session)def _write_submit_user_row(session: dict, text: Any, display_kind: str | None,@@ -582,8 +581,10 @@ def _write_submit_user_row(session: dict, text: Any, display_kind: str | None,``accept_metadata`` merges into ``display_metadata`` (the busy-queue accept's never-drainedmarker, retired by ``reopen_session`` — #125577).Returns None when nothing was written (no key / non-text / store unavailable / failed write)."""- key = session.get("session_key")- if not key or not isinstance(text, str) or not text.strip():+ # ``session_key`` is only an "is this a real session" probe — the row is written to ``target`` below,+ # which a rotation can already have moved off ``session_key`` (#123545). One guard, one value: the+ # writer must not read a different key than the one it checks.+ if not session.get("session_key") or not isinstance(text, str) or not text.strip():return Nonefrom agent.context_compressor import _DB_PERSISTED_MARKERfrom agent.message_metadata import stamp_message_timestamp, stamp_message_uid