Skip to content

The agent that grows with you

fix(gateway): reject unstamped durable ordinal rewinds

fangliquanflq79b7d969d390
diff --git a/run_agent.py b/run_agent.py
index 35976b6fe63..257aab53476 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -8539,6 +8539,7 @@ class AIAgent:
conversation_history = _turn_db.get_messages_as_conversation(
self.session_id,
repair_alternation=True,
+ include_row_ids=True,
)
# Long model/tool/compression turns outlive a fixed TTL. Refresh
diff --git a/tests/run_agent/test_cross_process_turn_lease.py b/tests/run_agent/test_cross_process_turn_lease.py
index 847a888abd5..a248dc31901 100644
--- a/tests/run_agent/test_cross_process_turn_lease.py
+++ b/tests/run_agent/test_cross_process_turn_lease.py
@@ -109,6 +109,10 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):
"reload",
"release",
]
+ assert db.events[2][2] == {
+ "repair_alternation": True,
+ "include_row_ids": True,
+ }
assert any(
kind == "lifecycle"
and text
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 6e5b6c43af0..a02b01c69cf 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -2929,8 +2929,17 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch, omit_messag
def get_ancestor_display_prefix(self, _sid):
return []
- def get_messages_as_conversation(self, target, include_ancestors=False, repair_alternation=False, **_kwargs):
- captured.setdefault("history_calls", []).append((target, include_ancestors))
+ def get_messages_as_conversation(
+ self,
+ target,
+ include_ancestors=False,
+ repair_alternation=False,
+ include_row_ids=False,
+ **_kwargs,
+ ):
+ captured.setdefault("history_calls", []).append(
+ (target, include_ancestors, include_row_ids)
+ )
return (
[
{"role": "user", "content": "root prompt"},
@@ -2975,9 +2984,9 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch, omit_messag
assert resp["result"]["messages"] == expected
assert resp["result"]["message_count"] == (1 if omit_messages else 2)
assert resp["result"]["messages_omitted"] is omit_messages
- expected_calls = [(target, False)] if omit_messages else [
- (target, False),
- (target, True),
+ expected_calls = [(target, False, True)] if omit_messages else [
+ (target, False, False),
+ (target, True, False),
]
assert captured["history_calls"] == expected_calls
@@ -5069,10 +5078,10 @@ def test_prompt_submit_truncation_falls_back_to_sid_when_session_key_null(monkey
replaced.append((key, list(messages)))
history = [
- {"role": "user", "content": "first"},
- {"role": "assistant", "content": "reply 1"},
- {"role": "user", "content": "second"},
- {"role": "assistant", "content": "reply 2"},
+ {"_row_id": 101, "role": "user", "content": "first"},
+ {"_row_id": 102, "role": "assistant", "content": "reply 1"},
+ {"_row_id": 103, "role": "user", "content": "second"},
+ {"_row_id": 104, "role": "assistant", "content": "reply 2"},
]
server._sessions["null-key-trunc-sid"] = _session(
history=list(history), session_key=None
@@ -5089,6 +5098,7 @@ def test_prompt_submit_truncation_falls_back_to_sid_when_session_key_null(monkey
"params": {
"session_id": "null-key-trunc-sid",
"text": "new turn",
+ "truncate_before_row_id": 103,
"truncate_before_user_ordinal": 1,
"confirm_truncate": True,
},
@@ -5186,6 +5196,56 @@ def test_prompt_submit_refuses_ordinal_only_when_history_has_row_ids(monkeypatch
server._sessions.pop("ordinal-only-durable-sid", None)
+def test_prompt_submit_refuses_ordinal_only_when_durable_history_is_unstamped(monkeypatch):
+ """Durability comes from state.db, not optional stamps on the live copy."""
+ replaced = []
+ history = [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "reply 1"},
+ {"role": "user", "content": "second"},
+ {"role": "assistant", "content": "reply 2"},
+ ]
+
+ class _FakeDB:
+ def get_messages_as_conversation(self, key, **kwargs):
+ assert key == "session-key"
+ assert kwargs["include_row_ids"] is True
+ return [dict(message, _row_id=100 + index) for index, message in enumerate(history)]
+
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
+ replaced.append((key, list(messages)))
+
+ server._sessions["unstamped-durable-sid"] = _session(history=list(history))
+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())
+ monkeypatch.setattr(
+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+ monkeypatch.setattr(
+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+
+ try:
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "unstamped-durable-sid",
+ "text": "retry",
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ }
+ )
+
+ assert resp["error"]["code"] == 4004
+ assert "truncate_before_row_id" in resp["error"]["message"]
+ assert server._sessions["unstamped-durable-sid"]["history"] == history
+ assert replaced == []
+ finally:
+ server._sessions.pop("unstamped-durable-sid", None)
+
+
def test_prompt_submit_truncates_by_row_id(monkeypatch):
"""#82959: prompt.submit with truncate_before_row_id must cut at the target row id."""
replaced = []
@@ -5394,10 +5454,10 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):
replaced.append((key, list(messages)))
history = [
- {"role": "user", "content": "first"},
- {"role": "assistant", "content": "ok"},
- {"role": "user", "content": "second"},
- {"role": "assistant", "content": "done"},
+ {"_row_id": 101, "role": "user", "content": "first"},
+ {"_row_id": 102, "role": "assistant", "content": "ok"},
+ {"_row_id": 103, "role": "user", "content": "second"},
+ {"_row_id": 104, "role": "assistant", "content": "done"},
]
server._sessions["empty-trunc-sid"] = _session(history=list(history))
monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())
@@ -5417,6 +5477,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):
"params": {
"session_id": "empty-trunc-sid",
"text": "fresh typed message",
+ "truncate_before_row_id": 101,
"truncate_before_user_ordinal": 0,
"confirm_truncate": True,
},
@@ -5433,6 +5494,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):
"params": {
"session_id": "empty-trunc-sid",
"text": "fresh typed message",
+ "truncate_before_row_id": 101,
"truncate_before_user_ordinal": 0,
"confirm_truncate": True,
"confirm_empty_truncate": falsey,
@@ -5481,10 +5543,10 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):
replaced.append((key, list(messages)))
history = [
- {"role": "user", "content": "first"},
- {"role": "assistant", "content": "ok"},
- {"role": "user", "content": "second"},
- {"role": "assistant", "content": "done"},
+ {"_row_id": 101, "role": "user", "content": "first"},
+ {"_row_id": 102, "role": "assistant", "content": "ok"},
+ {"_row_id": 103, "role": "user", "content": "second"},
+ {"_row_id": 104, "role": "assistant", "content": "done"},
]
server._sessions["confirm-empty-sid"] = _session(
agent=_Agent(), history=list(history)
@@ -5504,6 +5566,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):
"params": {
"session_id": "confirm-empty-sid",
"text": "first",
+ "truncate_before_row_id": 101,
"truncate_before_user_ordinal": 0,
"confirm_truncate": True,
"confirm_empty_truncate": True,
@@ -10754,6 +10817,9 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):
def __init__(self):
self.replaced = []
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ return []
+
def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
@@ -10811,6 +10877,9 @@ def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):
server._sessions["trunc-fail-sid"] = sess
class _FailDb:
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ return []
+
def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
raise OSError("disk full")
@@ -10903,6 +10972,9 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):
def __init__(self):
self.replaced = []
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ return []
+
def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
@@ -18173,6 +18245,9 @@ def test_personality_marker_does_not_shift_truncate_ordinal(monkeypatch):
def __init__(self):
self.replaced = []
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ return []
+
def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
@@ -18280,6 +18355,9 @@ def test_prompt_submit_truncation_archives_instead_of_deleting(monkeypatch):
self._target()
class _StubDb:
+ def get_messages_as_conversation(self, *_args, **_kwargs):
+ return []
+
def replace_messages(
self, session_id, messages, active_only=False, archive_dropped=False
):
diff --git a/tests/tui_gateway/test_undo_command.py b/tests/tui_gateway/test_undo_command.py
index 6a5739b6aae..4472cf8e2b1 100644
--- a/tests/tui_gateway/test_undo_command.py
+++ b/tests/tui_gateway/test_undo_command.py
@@ -106,5 +106,7 @@ def test_undo_returns_prefill_with_target_text(server, session_with_history):
# Default /undo backs up one user turn — "question 3"
assert result["message"] == "question 3"
assert "Undid" in result["notice"]
+ assert s["history"]
+ assert all("_row_id" in message for message in s["history"])
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index fd2feabd452..71fe628a35f 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -72,6 +72,29 @@ def _find_user_turn_by_row_id(history: list, target_row_id: int):
return None
+def _load_durable_truncation_history(session: dict, fallback_sid: str = ""):
+ """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 "")
+ if not session_key:
+ return []
+ try:
+ with _session_db(session) as db:
+ get_conv = getattr(db, "get_messages_as_conversation", None)
+ if not callable(get_conv):
+ return None
+ history = get_conv(
+ session_key, repair_alternation=True, include_row_ids=True
+ )
+ except Exception:
+ logger.debug(
+ "prompt.submit: failed loading durable history for session %s",
+ session_key,
+ exc_info=True,
+ )
+ return None
+ return history if isinstance(history, list) else None
+
+
def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):
"""Resolve ``truncate_before_row_id`` to ``(user_ordinal, history_index)``.
@@ -85,35 +108,8 @@ def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):
if hit is not None:
return hit
- session_key = str(session.get("session_key") or "")
- if not session_key:
- return None
-
- try:
- db = _get_db()
- except Exception:
- db = None
- if db is None:
- return None
-
- get_conv = getattr(db, "get_messages_as_conversation", None)
- if not callable(get_conv):
- return None
-
- try:
- db_history = get_conv(
- session_key, repair_alternation=True, include_row_ids=True
- )
- except Exception:
- logger.debug(
- "prompt.submit: failed loading DB history for row_id %s session %s",
- target_row_id,
- session_key,
- exc_info=True,
- )
- return None
-
- if not isinstance(db_history, list):
+ db_history = _load_durable_truncation_history(session)
+ if db_history is None:
return None
# Heal missing in-memory stamps when the live list still lines up 1:1 with
@@ -495,12 +491,26 @@ def _(rid, params: dict) -> dict:
if err is not None:
return err
else:
- # Once active user turns carry durable row ids, an ordinal-only
- # target is an unsafe downgrade: renderer and gateway ordinals
- # can diverge after compaction/rebuild while the row id remains
- # stable. Require the client to prove which durable turn it
- # means instead of persisting a potentially mis-aimed cut.
- if any(_message_row_id(history[h_idx]) is not None for h_idx in user_indices):
+ if client_ordinal < 0 or client_ordinal >= len(user_indices):
+ return _err(
+ rid, 4018, "target user message is no longer in session history"
+ )
+ # Durability is a state.db property, not an optional annotation
+ # on the live copy. Resume/reload paths historically omitted
+ # _row_id stamps, which made an ordinal-only request look safe
+ # even though it could destructively replace a long transcript.
+ # If the durable state cannot be read, fail closed too: absence
+ # of proof is not proof that this is an ephemeral conversation.
+ has_stamped_user = any(
+ _message_row_id(history[h_idx]) is not None
+ for h_idx in user_indices
+ )
+ durable_history = (
+ []
+ if has_stamped_user
+ else _load_durable_truncation_history(session, sid)
+ )
+ if has_stamped_user or durable_history is None or durable_history:
logger.warning(
"prompt.submit: REFUSED ordinal-only truncation of durable "
"session %s (ordinal=%d); truncate_before_row_id required",
@@ -1436,6 +1446,7 @@ def register(server) -> None:
_message_row_id,
_mem_db_pair_agrees,
_find_user_turn_by_row_id,
+ _load_durable_truncation_history,
_resolve_truncate_row_id,
_coerce_truncate_int,
_reconcile_client_ordinal,
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index fab90809f55..bc3579b7940 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -541,7 +541,7 @@ def _(rid, params: dict) -> dict:
# inspection/export must show what is actually stored.
if omit_messages:
raw_history = db.get_messages_as_conversation(
- target, repair_alternation=True
+ target, repair_alternation=True, include_row_ids=True
)
display_history = []
else:
@@ -627,7 +627,7 @@ def _(rid, params: dict) -> dict:
# display copy stays verbatim.
if omit_messages:
raw_history = db.get_messages_as_conversation(
- target, repair_alternation=True
+ target, repair_alternation=True, include_row_ids=True
)
display_history = []
else:
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 2e1d0d95b98..e5b64c4bd3a 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -916,7 +916,9 @@ def _(rid, params: dict) -> dict:
# lands on a durable user;user pair would otherwise re-fire the
# pre-request repair on every request from here on.
try:
- active = db.get_messages_as_conversation(session_key, repair_alternation=True)
+ active = db.get_messages_as_conversation(
+ session_key, repair_alternation=True, include_row_ids=True
+ )
except Exception:
active = []
with session["history_lock"]: