The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent,gateway): map a resumed truncation target onto its repaired live carrier
Brooklyn Nicholson6d28ff39b774
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex d388b12d286..13dceef8aa5 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -7343,9 +7343,15 @@ def test_prompt_submit_resolves_row_id_swallowed_by_plain_user_merge(monkeypatchdef _fake_session_db(_session):yield fake_db- live = [- {k: v for k, v in message.items() if k != "_row_id"} for message in verbatim- ]+ # Production cold resume materializes the live history from the DB with+ # repair_alternation=True (server._load_resume_transcript), stamps kept:+ # rows 303/304 collapse into ONE live carrier at 303, so 304 has no live+ # user ordinal. The un-repaired DB read finds 304 as physical ordinal 2,+ # but the live list only has user ordinals 0/1 — resolution must map the+ # DB row onto the repaired live carrier instead of trusting the same+ # ordinal against a list that cannot have it.+ live = copy.deepcopy(repaired)+ assert live[2]["_row_id"] == 303server._sessions["plain-merge-sid"] = _session(history=list(live))monkeypatch.setattr(server, "_session_db", _fake_session_db)monkeypatch.setattr(server, "_get_db", lambda: fake_db)@@ -7369,6 +7375,8 @@ def test_prompt_submit_resolves_row_id_swallowed_by_plain_user_merge(monkeypatcherr = resp.get("error")assert err is None, errassert len(replaced) == 1+ # The cut retains 303: deriving it from the physical durable prefix+ # keeps the inner row boundary instead of collapsing the pair.assert [m["content"] for m in replaced[0][1]] == ["first","reply 1",diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 09cd3cae8e4..743ae91cbfe 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -59,7 +59,13 @@ def _mem_db_pair_agrees(mem, db_msg) -> bool:def _find_user_turn_by_row_id(history: list, target_row_id: int):- """``(user_ordinal, history_index)`` for ``target_row_id``, or None."""+ """``(user_ordinal, history_index)`` for ``target_row_id``, or None.++ Exact ``_row_id`` matches only. An id absorbed into a merge carrier must NOT+ resolve here: the carrier's own index cuts the whole merged pair away, but a+ rewind aimed at the absorbed row has to retain the carrier's earlier half —+ that mapping is `_resolve_truncate_row_id`'s durable-prefix path.+ """return next(((u_ord, h_idx) for u_ord, h_idx in enumerate(_history_user_indices(history))if _message_row_id(history[h_idx]) == target_row_id), None)@@ -90,13 +96,22 @@ def _load_durable_truncation_history(def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):- """Resolve ``truncate_before_row_id`` to ``(user_ordinal, history_index)``: in-memory- stamps first, else the durable transcript mapped onto the live list by user ordinal.- Never falls back to a client-supplied ordinal — unknown row ids refuse.+ """Resolve ``truncate_before_row_id`` against the live list: a+ ``(user_ordinal, history_index)`` pair, or — when the target is a durable+ row absorbed into a repaired live carrier — a triple appending the+ physical ``durable_prefix`` to cut from. None refuses (fail closed);+ a client-supplied ordinal is never trusted as a fallback.Prefer in-memory ``_row_id`` / ``row_id`` stamps. When a live turn rewrote ``session["history"]``without stamps (provider-format messages), load the session's durable transcript with``include_row_ids=True`` and map the matched user-turn ordinal onto the live list. See #82959.++ A cold resume/reload materializes the live history with ``repair_alternation=True``, so the+ live list is the REPAIRED projection of the physical rows: a user;user run is merged into+ its first row and the absorbed rows' ids have no live ordinal. When the physical target row+ lives inside such a merged carrier, resolving to the carrier's own index would cut the whole+ pair (losing the unanswered earlier half); instead the durable prefix — the physical rows+ strictly before the target — is returned so the cut keeps the inner row boundary (#94486)."""if (hit := _find_user_turn_by_row_id(history, target_row_id)) is not None:return hit@@ -125,14 +140,56 @@ def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):return Nonedb_ord, db_idx = db_hitmem_user_indices = _history_user_indices(history)- # Same-ordinal mapping across lists that can still diverge (the live list itself may- # have been materialized from a repaired, merged view on resume, shifting every later- # user ordinal relative to the physical rows): trust the mapping only when the mapped- # live turn shows the same content as the durable target.- if db_ord >= len(mem_user_indices) or not _mem_db_pair_agrees(+ if db_ord < len(mem_user_indices) and _mem_db_pair_agrees(history[mem_user_indices[db_ord]], db_history[db_idx]):- return None- return db_ord, mem_user_indices[db_ord]+ # Same-ordinal mapping across aligned lists: the live turn at that user+ # ordinal shows the same content as the durable target.+ return db_ord, mem_user_indices[db_ord]+ # The live list can be the REPAIRED projection of these physical rows (a cold+ # resume/reload materializes session["history"] with repair_alternation=True):+ # the user;user run ending in the target row is merged into its FIRST row, so+ # every user ordinal after the run shifts down and the target has no live+ # ordinal of its own. Map the durable row onto the merge survivor that owns it+ # — the carrier whose own or absorbed id names the target — gated on the+ # carrier holding the durable target's text (repair folds a run with a+ # "\n\n" join, so the target's sanitized text is a whole part of the carrier).+ # The returned index keeps the merged pair: the prefix cut below carves the+ # durable target's own boundary out of it instead of dropping both rows.+ for u_ord, h_idx in enumerate(mem_user_indices):+ carrier = history[h_idx]+ absorbed_ids = [rid for rid in (carrier.get("_absorbed_row_ids") or ())+ if isinstance(rid, int)]+ if target_row_id != _message_row_id(carrier) and target_row_id not in absorbed_ids:+ continue+ if not _merge_carrier_holds_target_text(carrier, db_history[db_idx]):+ continue+ return u_ord, h_idx, db_history[:db_idx]+ return None+++def _merge_carrier_holds_target_text(carrier: dict, db_msg: dict) -> bool:+ """True when the live merge *carrier* plausibly holds the durable target row's+ text. ``_merge_consecutive_users`` joins a user;user run with ``"\\n\\n"`` (an+ empty side drops out), so the target's sanitized text either IS the carrier's+ content or appears in it as a whole ``"\\n\\n"``-delimited part. Both views are+ user-originated by construction (the caller only visits user turns)."""+ from agent.context_compressor import user_originated_turn_view+ from agent.memory_manager import sanitize_context+ mem_view = user_originated_turn_view(carrier)+ db_view = user_originated_turn_view(db_msg)+ if mem_view is None or db_view is None:+ # The caller only visits user turns; a None view means a non-user row+ # slipped in — refuse it.+ return False+ mem_content = mem_view.get("content")+ db_content = db_view.get("content")+ if not (isinstance(mem_content, str) and isinstance(db_content, str)):+ # A merged carrier is always plain-text (repair never merges multimodal+ # rows); a non-text durable target cannot live inside one.+ return False+ mem_text = sanitize_context(mem_content).strip()+ db_text = sanitize_context(db_content).strip()+ return db_text == mem_text or f"\n\n{db_text}" in mem_textdef _coerce_truncate_int(rid, value, param_name="truncate_before_user_ordinal"):@@ -281,14 +338,19 @@ 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)``: 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:return None, None, errtruncate_message_id = params.get("truncate_before_message_id")+ # The durable target was absorbed into a repaired live carrier: the physical+ # prefix carries the true row boundary for the cut (see _resolve_truncate_row_id).+ durable_prefix = None# Client ordinals count the full displayed lineage; after compression ancestors live in# display_history_prefix, so count their user turns once to translate ordinals.prefix_user_count = len(_history_user_indices(session.get("display_history_prefix") or []))@@ -306,6 +368,12 @@ def _resolve_truncation_ordinal(rid, sid, session, params, history):if target_row_id is not None:param_name, target_repr = "truncate_before_row_id", target_row_idfound_match = _resolve_truncate_row_id(session, history, target_row_id)+ if len(found_match or ()) == 3:+ # The durable target is a physical row absorbed into a repaired+ # live carrier: the pair stays, the cut keeps the target's own+ # row boundary (physical rows strictly before it).+ durable_prefix = found_match[2]+ found_match = found_match[:2]not_found = "target row_id %d not found for session %s (in-memory + durable)"else:param_name = "truncate_before_message_id"@@ -359,6 +427,8 @@ 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)+ if durable_prefix is not None:+ return ordinal, user_indices[ordinal], None, durable_prefixreturn ordinal, user_indices[ordinal], None@@ -370,11 +440,20 @@ 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", []))- ordinal, cut_index, err = _resolve_truncation_ordinal(rid, sid, session, params, history)+ resolved = _resolve_truncation_ordinal(rid, sid, session, params, history)+ ordinal, cut_index, err = resolved[0], resolved[1], resolved[2]+ durable_prefix = resolved[3] if len(resolved) > 3 else Noneif err is not None:return err, {}from agent.context_compressor import history_before_user_originated_turn- truncated, _live_view = history_before_user_originated_turn(history, cut_index)+ if durable_prefix is not None:+ # Durable-boundary cut: the target row is physically present but merged into+ # a repaired live carrier; the physical rows strictly before it are the+ # survivors — the carrier's earlier half stays, the absorbed target and+ # everything after it are replaced by the submitted turn.+ truncated, _live_view = [message.copy() for message in durable_prefix], None+ else:+ truncated, _live_view = history_before_user_originated_turn(history, cut_index)# Second gate: ordinal 0 would DELETE every durable row; wiping needs its own opt-in.if not truncated and history and not is_truthy_value(params.get("confirm_empty_truncate")):logger.warning(