Skip to content

The agent that grows with you

fix(tui_gateway): address the rotated tip when reading the transcript (#123545)

Halldrix8ded06be29cf
diff --git a/tests/tui_gateway/test_submit_row_session_target.py b/tests/tui_gateway/test_submit_row_session_target.py
index ae32b6ea77a..5e8b3e1dbe4 100644
--- a/tests/tui_gateway/test_submit_row_session_target.py
+++ b/tests/tui_gateway/test_submit_row_session_target.py
@@ -246,6 +246,64 @@ def test_message_react_targets_the_row_in_the_session_that_owns_it(monkeypatch,
db.close()
+def test_session_history_reads_the_continuation_after_a_rotation(monkeypatch, tmp_path):
+ """``session.history`` addresses the durable transcript by session. ``include_ancestors`` walks PARENT
+ pointers, so a stale ``session_key`` materializes root..parent and never the continuation — a
+ reconnect in the post-rotation window renders a transcript missing every turn since the rotation."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, session, agent, child = _rotated_session(monkeypatch, db)
+ try:
+ db.append_message(child, "user", content="sent after the rotation")
+ got = server.handle_request({"id": "h1", "method": "session.history", "params": {"session_id": sid}})
+ assert "result" in got, got
+ texts = [m.get("text") or m.get("content") for m in got["result"]["messages"]]
+ assert "sent after the rotation" in texts, (
+ f"session.history served the stale parent {key}, not the live {child}: {got['result']['messages']}")
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_out_of_band_probe_reads_the_continuation_after_a_rotation(monkeypatch, tmp_path):
+ """``_adopt_out_of_band_turns`` keyset-probes for foreign rows (a Telegram reply, a cron delivery)
+ written since the turn started. On a rotated session the parent holds none of them, so the probe
+ returns nothing and the model never sees the out-of-band turn — a regression of the contract this
+ function exists for (#42962/#86588)."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, session, agent, child = _rotated_session(monkeypatch, db)
+ try:
+ from tui_gateway import prompt_turn
+ # _adopt_out_of_band_turns reads _message_row_id, which methods_prompt publishes onto server's
+ # globals at bind_module time (prompt_turn's own module never imports it). Importing the module
+ # here runs that binding — the same order server.py's own import loop produces.
+ from tui_gateway import methods_prompt # noqa: F401
+ assert hasattr(server, "_message_row_id"), "the bind seam must publish _message_row_id"
+ # Stamp the in-memory history with the row ids the rotation actually created, so `seen` is the
+ # newest row the agent's own flush wrote and the foreign row is strictly newer.
+ with session["history_lock"]:
+ session["history"] = [
+ dict(r, _row_id=r["_row_id"]) for r in db.get_messages_as_conversation(child, include_row_ids=True)
+ ]
+ session["history_version"] = 1
+ stamped = [m["_row_id"] for m in session["history"]]
+ assert stamped, "the rotation must have created rows to stamp"
+ seen = max(stamped)
+ # Another surface appends to the session the LIVE agent writes to, after those rows.
+ foreign = db.append_message(child, "user", content="a Telegram reply that arrived mid-turn")
+ assert foreign > seen, f"the foreign row {foreign} must sort after the in-flight rows {stamped}"
+
+ # Call the REBOUND copy on server: bind_module re-creates each body against server's globals, and
+ # that copy is what production runs. prompt_turn's original still points at its own module dict,
+ # where _message_row_id (published by methods_prompt) was never bound.
+ server._adopt_out_of_band_turns(session)
+ texts = [str(m.get("content")) for m in session["history"]]
+ assert "a Telegram reply that arrived mid-turn" in texts, (
+ f"the out-of-band probe read the stale parent {key} and adopted nothing: {texts}")
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
def test_unrotated_session_keeps_writing_to_session_key(monkeypatch, tmp_path):
"""The ordinary case is unchanged: no rotation, the row lands under session_key as before."""
db = SessionDB(db_path=tmp_path / "state.db")
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index d26c4d793e9..a815a9a5f33 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -68,7 +68,10 @@ def _find_user_turn_by_row_id(history: list, target_row_id: int):
def _load_durable_truncation_history(
session: dict, fallback_sid: str = "", repair_alternation: bool = True):
"""Load the durable live-replay transcript, or None when it cannot be proven safe."""
- session_key = str(session.get("session_key") or fallback_sid or "")
+ # Same stale-key hazard as the submit row and the out-of-band probe: a compression rotation moves the
+ # live tip off session_key, and this is the load every adoption path replays from — reading the parent
+ # returns a transcript without the continuation (#123545).
+ session_key = _submit_row_target_key(session) or str(fallback_sid or "")
if not session_key:
return []
try:
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index b96ad5739fa..3024a61fa38 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1915,7 +1915,12 @@ def _(rid, params: dict, session: dict) -> dict:
@_session_method("session.history")
def _(rid, params: dict, session: dict) -> dict:
history = list(session.get("history", []))
- if session.get("session_key"):
+ # Address the session the live agent writes to, not session_key: a compression rotation moves the
+ # tip mid-session, and include_ancestors walks parent pointers, so a stale parent materializes
+ # root..parent and NEVER the continuation — a reconnect in that window renders a transcript missing
+ # every turn since the rotation (#123545).
+ row_session = _submit_row_target_key(session)
+ if row_session:
with _session_db(session) as db:
if db is not None:
# include_row_ids: the durable row id is how clients address a persisted turn (reactions,
@@ -1925,7 +1930,7 @@ def _(rid, params: dict, session: dict) -> dict:
# stamp, so an unstamped read here silently strips the one durable address clients can
# use. See #87059.
history = db.get_messages_as_conversation(
- session["session_key"], include_ancestors=True, include_row_ids=True)
+ row_session, include_ancestors=True, include_row_ids=True)
return _ok(rid, {"count": len(history), "messages": _history_to_messages(history, profile_home=session.get("profile_home"))})
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index fcf46b7e569..511d4005f13 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -525,9 +525,12 @@ def _adopt_out_of_band_turns(session: dict) -> None:
def _foreign(rid) -> bool:
return _below_ceiling(rid) and rid > seen
# Keyset probe first: the common turn has nothing to adopt and must not pay a full transcript decode.
+ # Address the live session, not session_key: a rotation moves the tip mid-session, so the parent
+ # holds none of the foreign rows (Telegram reply, cron) this function exists to adopt and the model
+ # silently never sees them (#123545).
with _session_db(session) as db:
try:
- newer = db.get_messages(session["session_key"], after_id=seen) if db is not None else []
+ newer = db.get_messages(_submit_row_target_key(session), after_id=seen) if db is not None else []
except Exception:
logger.debug("out-of-band history probe failed; turn runs on the in-memory history", exc_info=True)
return