From f86693c2f9c073cb38694aef009ef7b6ab8bc3f5 Mon Sep 17 00:00:00 2001 From: dsad Date: Sun, 2 Aug 2026 11:53:32 +0530 Subject: [PATCH] fix(tui): fail closed when prompt.submit cannot persist history truncation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop edit / regenerate / restore-checkpoint send truncate_before_user_ordinal on prompt.submit. The handler rewrote session['history'] first, then called replace_messages, and on failure only printed to stderr and still started the turn. When the durable write fails, in-memory history is already truncated and history_version is bumped while state.db still holds the pre-edit 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. Fix: persist first; only then mutate memory. On failure return 5008 and leave memory/DB unchanged. Based on #72876 by @necoweb3. Adapted: the handler moved from tui_gateway/server.py to tui_gateway/methods_prompt.py since the PR's base. --- tests/test_tui_gateway_server.py | 52 ++++++++++++++++++++++++++++++++ tui_gateway/methods_prompt.py | 27 +++++++++++++++-- 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py index 0240817483..e2cde67ead 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 8983070bbd..7e3157544e 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()