Skip to content

The agent that grows with you

fix(tui): fail closed when prompt.submit cannot persist history truncation

dsadf86693c2f9c0
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 02408174835..e2cde67eadd 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -8893,6 +8893,58 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):
server._sessions.pop("sid", None)
+def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):
+ """If replace_messages fails during edit/regenerate truncate, do not run the turn.
+
+ Memory-first + fail-open left session['history'] short while state.db kept
+ the old tail. The agent flush then appends the new exchange on top of the
+ 'undone' turns — durable zombie history. Write first; on failure leave
+ memory and DB unchanged and return 5008.
+ """
+ original_history = [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "first reply"},
+ {"role": "user", "content": "second"},
+ {"role": "assistant", "content": "second reply"},
+ ]
+ sess = _session(history=list(original_history))
+ server._sessions["trunc-fail-sid"] = sess
+
+ class _FailDb:
+ def replace_messages(self, session_id, messages):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(server, "_get_db", lambda: _FailDb())
+ monkeypatch.setattr(
+ server, "_start_inflight_turn", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+ monkeypatch.setattr(
+ server, "_start_agent_build", lambda *a, **k: pytest.fail("must not start a turn")
+ )
+
+ try:
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "trunc-fail-sid",
+ "text": "edited second",
+ "truncate_before_user_ordinal": 1,
+ },
+ }
+ )
+ assert "error" in resp
+ assert resp["error"]["code"] == 5008
+ assert "truncat" in resp["error"]["message"].lower() or "persist" in resp["error"]["message"].lower()
+ # Memory left intact — same list contents as before the refused cut.
+ assert sess["history"] == original_history
+ assert sess["history_version"] == 0
+ assert sess.get("running") is not True
+ finally:
+ server._sessions.pop("trunc-fail-sid", None)
+
+
# ---------------------------------------------------------------------------
# session.interrupt must only cancel pending prompts owned by the calling
# session — it must not blast-resolve clarify/sudo/secret prompts on
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 8983070bbd0..7e3157544e0 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -210,13 +210,34 @@ def _(rid, params: dict) -> dict:
len(truncated),
ordinal,
)
- session["history"] = truncated
- session["history_version"] = int(session.get("history_version", 0)) + 1
+ # Write-before-memory (mirrors gateway hygiene / manual /compress):
+ # persist the truncated transcript first. If replace_messages fails
+ # after we already rewrote session["history"], the turn still runs
+ # against the short list while state.db keeps the old tail. The
+ # agent flush is append-only for history-dict identities, so the
+ # new exchange is appended on top of the "undone" turns — durable
+ # zombie history on resume, and the edit/regenerate never sticks.
+ # Fail closed: refuse the turn and leave memory/DB unchanged.
if (db := _get_db()) is not None:
try:
db.replace_messages(session["session_key"], truncated)
except Exception as exc:
- print(f"[tui_gateway] prompt.submit: replace_messages failed: {exc}", file=sys.stderr)
+ logger.error(
+ "prompt.submit: replace_messages failed for session %s "
+ "(ordinal=%d); refusing turn so memory and DB stay "
+ "aligned: %s",
+ sid,
+ ordinal,
+ exc,
+ exc_info=True,
+ )
+ return _err(
+ rid,
+ 5008,
+ f"failed to persist history truncation: {exc}",
+ )
+ session["history"] = truncated
+ session["history_version"] = int(session.get("history_version", 0)) + 1
session["running"] = True
session["_turn_cancel_requested"] = False
session["last_active"] = time.time()