The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): hold the session busy for a whole manual compaction
kshitijk4poor06b94c946d70
diff --git a/tests/tui_gateway/test_busy_compression_demotion.py b/tests/tui_gateway/test_busy_compression_demotion.pyindex 295b81f6252..c6187e077cb 100644--- a/tests/tui_gateway/test_busy_compression_demotion.py+++ b/tests/tui_gateway/test_busy_compression_demotion.py@@ -171,3 +171,54 @@ def test_session_redirect_queues_while_compressing(monkeypatch):assert resp["result"]["status"] == "queued"assert seen == []+++# ── manual compaction holds the session busy (#133504) ────────────────────++def test_submit_during_manual_compress_is_queued_and_reply_persists(monkeypatch):+ """A prompt sent while session.compress runs its LLM summary used to be admitted on the idle+ session, snapshot history_version N, and lose its reply when the compaction committed N+1."""+ import agent.conversation_compression_manual as ccm++ gate, entered = threading.Event(), threading.Event()++ def fake_compress_now(agent, msgs, request, **kw):+ entered.set()+ gate.wait(5)+ return types.SimpleNamespace(status="compressed", removed=4,+ after_messages=[{"role": "user", "content": "[summary]"}, *msgs[-2:]])++ def fake_turn(rid, sid, session, text, **kw): # the drained turn: snapshot, reply, commit+ with session["history_lock"]:+ hist, ver = list(session["history"]), int(session["history_version"])+ result = {"messages": [*hist, {"role": "user", "content": text}, {"role": "assistant", "content": "REPLY"}]}+ server._commit_turn_history(session, result, hist, ver)+ session["running"] = False++ monkeypatch.setattr(ccm, "compress_now", fake_compress_now)+ monkeypatch.setattr(server, "_run_prompt_submit", fake_turn)+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")+ for name in ("_status_update", "_emit", "_sync_session_key_after_compress", "_persist_queued_user_row",+ "_replace_queued_user_row_for_turn"):+ monkeypatch.setattr(server, name, lambda *a, **k: None)+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda _s: False)+ monkeypatch.setattr(server, "_session_info", lambda *a, **k: {})+ agent = types.SimpleNamespace(+ session_id="session-key", _cached_system_prompt="", tools=None, context_compressor=None,+ interrupt=lambda *a, **k: (_ for _ in ()).throw(AssertionError("compaction must not be interrupted")))+ history = [{"role": r, "content": f"m{i}"} for i, r in enumerate(["user", "assistant"] * 3)]+ session = _session(agent=agent, running=False, history=history)+ monkeypatch.setattr(server, "_sess", lambda params, rid: (session, None))+ monkeypatch.setattr(server, "_sess_nowait", lambda params, rid: (session, None))++ rpc = threading.Thread(target=server._methods["session.compress"], args=("r1", {"session_id": "sid"}))+ rpc.start()+ assert entered.wait(5)+ resp = server._handle_busy_submit("r2", "sid", session, "question", "ws-1")+ gate.set()+ rpc.join(5)++ assert resp["result"]["status"] == "queued"+ assert session["history"][-1]["content"] == "REPLY"+ assert session["history"][0]["content"] == "[summary]"+ assert session["running"] is Falsediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex d707b16c70d..745ba5f1a20 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -2154,9 +2154,9 @@ def _(rid, params: dict) -> dict:return errif session.get("running"):return _err(rid, 4009, busy_message("compress"))- sid = params.get("session_id", "")try:- return _compress_live(rid, sid, session, _str_param(params, "focus_topic"))+ with _manual_compress_turn(sid := params.get("session_id", ""), session):+ return _compress_live(rid, sid, session, _str_param(params, "focus_topic"))except CompressionLockHeld as e:_status_update(sid, "ready")from agent.manual_compression_feedback import describe_compression_lock_skipdiff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.pyindex 9e4f6b92c94..f97c6bef304 100644--- a/tui_gateway/methods_slash.py+++ b/tui_gateway/methods_slash.py@@ -359,7 +359,7 @@ def _compress_live_with_feedback(sid: str, session: dict, agent, arg: str, *, snAGGRESSIVE_UNSUPPORTED, compress_now, parse_compress_args, render_compress_result)from agent.manual_compression_feedback import describe_compression_lock_skip, summarize_manual_compressionfrom agent.model_metadata import estimate_request_tokens_rough- with _session_profile_runtime_scope(session):+ with _session_profile_runtime_scope(session), _manual_compress_turn(sid, session):with session["history_lock"]:before_messages = list(session.get("history", []))history_version = int(session.get("history_version", 0))diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex a3bdedf7a4b..5bdfe54229d 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -269,6 +269,8 @@ def _session_compression_in_flight(session: dict) -> bool:``_session_has_compression_in_flight``, #56391); this is the local-RPC twin. Bothblocking reads run off the event loop so a large state.db never freezes the dispatcher."""+ if session.get("_manual_compress_active"): # held before/after the DB lock row exists (#133504)+ return Trueagent = session.get("agent")sid = str(getattr(agent, "session_id", "") or "") or str(session.get("session_key") or "")if not sid:diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.pyindex 033d9860a2d..ee7d922f26d 100644--- a/tui_gateway/session_compression.py+++ b/tui_gateway/session_compression.py@@ -219,6 +219,24 @@ class CompressionLockHeld(Exception):super().__init__(f"Compression lock held: {holder or 'unknown'}")+def _manual_compress_turn(sid: str, session: dict):+ """Hold the session busy (``running``) for a whole manual compaction: snapshot, LLM summary, commit+ and session-key re-anchor. A prompt.submit arriving meanwhile takes the busy path (demoted to queue+ by ``_session_compression_in_flight``) instead of snapshotting a history version the compaction is+ about to bump, which dropped the turn's reply (#133504). The queued prompt drains on release."""+ with session["history_lock"]:+ if session.get("running"):+ raise RuntimeError(busy_message("compress"))+ session["running"] = session["_manual_compress_active"] = True+ try:+ yield+ finally:+ with session["history_lock"]:+ session["running"] = session["_manual_compress_active"] = False+ _drain_queued_prompt("__compress__", sid, session)++def _compress_session_history(session: dict, focus_topic: str | None = None, approx_tokens: int | None = None,before_messages: list | None = None, history_version: int | None = None,