The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): count every durable user row a merged carrier holds in the deep-cut gate
kshitijk4poor009fb2c98b5a
diff --git a/tests/tui_gateway/test_tui_gateway_server_deep_truncate.py b/tests/tui_gateway/test_tui_gateway_server_deep_truncate.pyindex 584e7767c13..e046292e70d 100644--- a/tests/tui_gateway/test_tui_gateway_server_deep_truncate.py+++ b/tests/tui_gateway/test_tui_gateway_server_deep_truncate.py@@ -52,20 +52,53 @@ def test_prompt_submit_refuses_deep_truncation_without_confirm(monkeypatch):assert _submit(confirm_deep_truncate=True).get("error") is Noneassert replaced == [history[:2]]- # Durable-carrier cut: the target (101) was absorbed into a repaired live carrier;+ # Durable-carrier cut: the target (150) was absorbed into a repaired live carrier;# the refusal counts live rows from the carrier on, never live minus physical.physical = [{"_row_id": 100, "role": "user", "content": "u0"},- {"_row_id": 101, "role": "user", "content": "u0b"}, *history[1:]]+ {"_row_id": 150, "role": "user", "content": "u0b"}, *history[1:]]_FakeDB.get_messages_as_conversation = lambda self, key, **_kw: [dict(m) for m in physical] # type: ignore[attr-defined]sess["running"] = False # the confirmed submit above left a (never-started) turn- sess["history"] = [{"_row_id": 100, "_absorbed_row_ids": [101], "role": "user",+ sess["history"] = [{"_row_id": 100, "_absorbed_row_ids": [150], "role": "user","content": "u0\n\nu0b"}, *history[1:]]- carrier = _submit(truncate_before_row_id=101)+ carrier = _submit(truncate_before_row_id=150)assert carrier["error"]["data"] == {"archived_messages": 6, "archived_user_turns": 3}finally:server._sessions.pop("deep-trunc-sid", None)+def test_deep_truncate_counts_every_durable_row_a_merged_carrier_holds(monkeypatch):+ """A user;user run repaired into one live carrier is several durable user turns: cutting at+ its first row archives all of them, so it needs confirm_deep_truncate like any deep cut."""+ replaced = []++ physical = [{"_row_id": 101, "role": "user", "content": "a"}, {"_row_id": 102, "role": "user", "content": "b"},+ {"_row_id": 103, "role": "user", "content": "c"}, {"_row_id": 104, "role": "assistant", "content": "reply"}]++ class _FakeDB:+ def get_messages_as_conversation(self, key, **_kwargs):+ return [dict(m) for m in physical]++ def replace_messages(self, key, messages, **_kwargs):+ replaced.append(list(messages))++ history = [{"_row_id": 101, "_absorbed_row_ids": [102, 103], "role": "user", "content": "a\n\nb\n\nc"},+ {"_row_id": 104, "role": "assistant", "content": "reply"}]+ sess = _session(history=list(history))+ server._sessions["deep-carrier-sid"] = sess+ monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)+ monkeypatch.setattr(server.threading, "Thread", lambda *a, **k: types.SimpleNamespace(start=lambda: None))+ try:+ refused = server.handle_request({"id": "1", "method": "prompt.submit", "params": {+ "session_id": "deep-carrier-sid", "text": "a", "truncate_before_row_id": 101,+ "confirm_truncate": True, "confirm_empty_truncate": True}})+ assert refused["error"]["code"] == 4033+ assert refused["error"]["data"]["archived_user_turns"] == 3+ assert sess["history"] == history and replaced == []+ finally:+ server._sessions.pop("deep-carrier-sid", None)++def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):"""Intentional restore/regenerate of the first user turn may wipe history."""diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 0cef613fda1..157a1865a7b 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -338,11 +338,11 @@ def _parse_truncation_params(rid, sid, session, params, history):def _resolve_truncation_ordinal(rid, sid, session, params, history):- """Resolve the truncation target to ``(ordinal, cut_index, err)``; on success also- ``durable_prefix`` (set when the durable target was absorbed into a repaired live- carrier, else None) and the live user-turn count. Refusals: unresolvable target- (4018, fail closed — never degrade a missing row_id/message_id into an ordinal- cut) -> ordinal drift (4030) -> ordinal-only on a durable session (4004)."""+ """Resolve the truncation target to ``(ordinal, cut_index, err)`` — with a fourth+ ``durable_prefix`` element when the durable target was absorbed into a repaired+ live carrier: unresolvable target (4018, fail closed — never degrade a missing+ row_id/message_id into an ordinal cut) -> ordinal drift (4030) -> ordinal-only on+ a durable session (4004)."""target_row_id, client_ordinal, err = _parse_truncation_params(rid, sid, session, params, history)if err is not None:@@ -427,22 +427,50 @@ def _resolve_truncation_ordinal(rid, sid, session, params, history):# BOTH ends: a negative ordinal would index user_indices[-1] and persist the loss.if ordinal < 0 or ordinal >= len(user_indices):return _stale(resolved_ordinal=ordinal)- return ordinal, user_indices[ordinal], None, durable_prefix, len(user_indices)+ if durable_prefix is not None:+ return ordinal, user_indices[ordinal], None, durable_prefix+ return ordinal, user_indices[ordinal], Nonedef _row_ids_of(messages) -> set:return {row_id for message in messages if isinstance((row_id := _message_row_id(message)), int)}+def _archived_user_turns(session, sid, history, cut_index, survivor_ids) -> int:+ """User turns a cut at *cut_index* drops. A repaired live carrier stands for its whole merged+ run (own id + ``_absorbed_row_ids``), which can mix real user rows with display markers+ (#94486): its turns are counted from the physical durable rows, and every id that cannot be+ classified there counts as a turn (fail closed). On a durable-carrier cut the run's rows+ before the target survive (*survivor_ids*)."""+ from agent.context_compressor import user_originated_turn_view+ physical = None+ archived = 0+ for h_idx in _history_user_indices(history):+ if h_idx < cut_index:+ continue+ message = history[h_idx]+ absorbed = [rid for rid in (message.get("_absorbed_row_ids") or ()) if isinstance(rid, int)]+ if not absorbed:+ archived += 1+ continue+ if physical is None:+ rows = _load_durable_truncation_history(session, sid, repair_alternation=False) or []+ physical = {_message_row_id(row): row for row in rows if isinstance(row, dict)}+ for rid in {_message_row_id(message), *absorbed} - survivor_ids - {None}:+ row = physical.get(rid)+ archived += row is None or user_originated_turn_view(row) is not None+ return archived++def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids):"""Rewind/regenerate cut under ``history_lock``: ``(err, survivor_fields)``; the fieldsare the client rowId-rebind payload."""history = _history_without_ephemeral_scaffolding(session.get("history", []))resolved = _resolve_truncation_ordinal(rid, sid, session, params, history)- ordinal, cut_index, err = resolved[:3]+ ordinal, cut_index, err = resolved[0], resolved[1], resolved[2]if err is not None:return err, {}- durable_prefix, user_turn_count = resolved[3:]+ durable_prefix = resolved[3] if len(resolved) > 3 else Nonefrom agent.context_compressor import history_before_user_originated_turnif durable_prefix is not None:# Durable-boundary cut: the target row is physically present but merged into@@ -464,7 +492,7 @@ def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids"resubmit with confirm_empty_truncate=true if this is intended"), {}# Depth gate: a valid anchor can still name a stale row; tail regenerate / edit-last# drop exactly one user turn, deeper cuts need confirm_deep_truncate.- archived_user_turns = user_turn_count - ordinal+ archived_user_turns = _archived_user_turns(session, sid, history, cut_index, _row_ids_of(truncated))if archived_user_turns > 1 and not is_truthy_value(params.get("confirm_deep_truncate")):# A durable-carrier cut's ``truncated`` is physical rows: count the live cut instead.archived_messages = len(history) - (