The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(sessions): pair tool-call uids in O(K) on flush and only when needed on restore
kshitijk4poor30050851f766
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex ff8203b4e93..8235e5108e2 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1319,11 +1319,11 @@ def _apply_context_engine_selection(# The engine may hand back the ``conversation_messages`` clones (or its own dicts) that still# carry persistence-only fields; the request copy was stripped BEFORE this hook, so strip the# selection too or those fields reach the provider. Dicts without them pass through as-is.- if not any(key in m for m in selected for key in PERSISTENCE_ONLY_MESSAGE_FIELDS):+ if all(PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(m) for m in selected):return selectedreturn [- {k: v for k, v in m.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}- if any(key in m for key in PERSISTENCE_ONLY_MESSAGE_FIELDS) else m+ m if PERSISTENCE_ONLY_MESSAGE_FIELDS.isdisjoint(m)+ else {k: v for k, v in m.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS}for m in selected]logger.warning(diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex e2db82e2592..f250efb4e1d 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -156,9 +156,11 @@ def resolve_tool_call_uid(index: MutableMapping[str, str], tool_call_id: Any) ->return None-def tool_call_uid_from_history(messages: Any, tool_index: int) -> Optional[str]:+def tool_call_uid_from_history(messages: Any, tool_index: int, owners: Optional[dict] = None) -> Optional[str]:"""Resolve a tool-result dict's uid from the nearest preceding assistant dict in ``messages`` that- named its ``tool_call_id`` (the cross-flush case: the assistant row landed in an earlier batch)."""+ named its ``tool_call_id`` (the cross-flush case: the assistant row landed in an earlier batch).+ ``owners`` memoizes each assistant's (named variants, uid index) across one flush's results, so K+ parallel results of one assistant cost O(K) variant work instead of O(K^2)."""if not isinstance(messages, list) or not (0 <= tool_index < len(messages)):return Nonetool_msg = messages[tool_index]@@ -174,11 +176,19 @@ def tool_call_uid_from_history(messages: Any, tool_index: int) -> Optional[str]:continueif prior.get("role") == "user":return None # a tool result never pairs across a user turn- if prior.get("role") != "assistant" or result_variants.isdisjoint(_named_tool_call_variants(prior)):+ if prior.get("role") != "assistant":+ continue+ entry = owners.get(id(prior)) if owners is not None else None+ if entry is None:+ index: dict = {}+ index_tool_call_uids(index, prior)+ entry = (frozenset(_named_tool_call_variants(prior)), index)+ if owners is not None:+ owners[id(prior)] = entry+ named, index = entry+ if result_variants.isdisjoint(named):continue# The nearest assistant naming this id owns the result: its uid, or none if it has no map (legacy).- index: dict = {}- index_tool_call_uids(index, prior)return resolve_tool_call_uid(index, tool_call_id)return Nonediff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex c9689ebe82e..cf9bf2a78e8 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -2424,7 +2424,11 @@ def _estimate_message_tokens_cached(msg: Any, image_cost: int) -> int:return _estimate_message_tokens_without_images(msg), _count_image_tokens(msg, 1)try:pins: list = []- key = _msg_fingerprint(msg, pins)+ # Persistence-only fields (identity, timestamps, display metadata) never reach the estimate: keep them+ # out of the key so stamping them neither costs a walk nor misses the memo.+ key = _msg_fingerprint(+ {k: v for k, v in msg.items() if k not in PERSISTENCE_ONLY_MESSAGE_FIELDS} if type(msg) is dict else msg,+ pins)hash(key)except Exception:text, images = _compute()diff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 04913b06b2b..8c0f6e79785 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -258,6 +258,7 @@ def _db_flush_collect(agent, messages: List[Dict], conversation_history: Optionapending_cli_message = getattr(agent, "_pending_cli_user_message", None)batch_rows: List[Dict[str, Any]] = []batch_msgs: List[Dict] = []+ tool_uid_owners: dict = {} # tool_call_uid_from_history memo; the scanned dicts outlive this loopfor msg_idx in range(_db_flush_scan_start(agent, messages), len(messages)):msg = messages[msg_idx]# Append-only flush: a mid-turn persist of scaffolding would commit a synthetic turn the end-of-turn@@ -279,7 +280,7 @@ def _db_flush_collect(agent, messages: List[Dict], conversation_history: Optionaif msg.get("role") == "tool" and not msg.get(TOOL_CALL_UID):# A result whose call was flushed in an earlier batch: pair it with the uid that assistant row# minted (same-batch pairing happens inside the insert).- if (tool_uid := tool_call_uid_from_history(messages, msg_idx)) is not None:+ if (tool_uid := tool_call_uid_from_history(messages, msg_idx, tool_uid_owners)) is not None:msg[TOOL_CALL_UID] = tool_uidbatch_rows.append(_db_flush_row(agent, msg, ov_idx == msg_idx or msg is pending_cli_message))batch_msgs.append(msg)diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 266ec46a7c7..2d16b784e7e 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -121,6 +121,18 @@ def _uid_map(value: Any) -> Dict[str, str]:return {k: v for k, v in value.items() if isinstance(k, str) and k and isinstance(v, str) and v}+def _restore_identity_columns(row: Any, msg: Dict[str, Any]) -> None:+ """The stored identity columns onto a restored dict under their live keys (NULL/empty add nothing)."""+ if row[MESSAGE_UID]:+ msg[MESSAGE_UID] = row[MESSAGE_UID]+ if absorbed := _uid_list(row["absorbed_message_uids"]):+ msg[ABSORBED_MESSAGE_UIDS] = absorbed+ if tool_uids := _uid_map(row["tool_call_uids"]):+ msg[TOOL_CALL_UIDS] = tool_uids+ if row["tool_call_uid"]:+ msg[TOOL_CALL_UID] = row["tool_call_uid"]++def _tool_call_uids_json(msg: Dict[str, Any]) -> Optional[str]:uids = _uid_map(msg.get(TOOL_CALL_UIDS) if TOOL_CALL_UIDS in msg else msg.get("tool_call_uids"))return json.dumps(uids, sort_keys=True) if uids else None@@ -389,14 +401,7 @@ class SessionMessagesMixin:msg["observed"] = Trueif row["_compressed_summary"]:msg["_compressed_summary"] = True- if row[MESSAGE_UID]:- msg[MESSAGE_UID] = row[MESSAGE_UID]- if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):- msg[ABSORBED_MESSAGE_UIDS] = absorbed- if row["tool_call_uids"] and (tool_uids := _uid_map(row["tool_call_uids"])):- msg[TOOL_CALL_UIDS] = tool_uids- if row["tool_call_uid"]:- msg[TOOL_CALL_UID] = row["tool_call_uid"]+ _restore_identity_columns(row, msg)if row["api_content"] is not None:msg["api_content"] = row["api_content"]if row["display_kind"] is not None:@@ -1606,7 +1611,10 @@ class SessionMessagesMixin:from hermes_state import _strip_background_review_harness, _strip_stale_tool_call_markersmessages = []exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {}- tool_uid_index: Dict[str, str] = {} # pairing-id variant -> uid, from the assistant rows read so far+ tool_uid_index: Dict[str, str] = {} # pairing-id variant -> uid, from the assistant rows indexed so far+ # Assistant rows since the last user row not yet indexed: only a result without a stored uid (an older+ # build's) needs the index, so rows this build wrote never pay for it. Indexed in order: same shadowing.+ unindexed_tool_owners: List[Dict[str, Any]] = []for row in rows:content = self._loaded_view_content(row["role"], self._decode_content(row["content"]))# Underscore-prefixed like ``_row_id``: transports strip it before the wire; compression's@@ -1619,13 +1627,9 @@ class SessionMessagesMixin:# the ENTIRE transcript on flush.if include_row_ids and row["id"] is not None:msg["_row_id"] = row["id"]- # The durable per-message id is part of the message, like ``timestamp``: restored on EVERY- # projection (ACP, gateway, CLI, TUI, compression adoption), never opt-in like ``_row_id``.- if row[MESSAGE_UID]:- msg[MESSAGE_UID] = row[MESSAGE_UID]- # The persisted merge witness: which rows a consecutive-user merge folded into this one.- if row["absorbed_message_uids"] and (absorbed := _uid_list(row["absorbed_message_uids"])):- msg[ABSORBED_MESSAGE_UIDS] = absorbed+ # The durable identity is part of the message, like ``timestamp``: restored on EVERY projection+ # (ACP, gateway, CLI, TUI, compression adoption), never opt-in like ``_row_id``.+ _restore_identity_columns(row, msg)msg.update((col, row[col]) for col in ("api_content", "display_kind") if row[col])if row["display_metadata"] and (decoded := self._decode_display_metadata(row["display_metadata"])) is not None:msg["display_metadata"] = decoded@@ -1647,19 +1651,20 @@ class SessionMessagesMixin:msg.update((col, _json_or(row[col], None, f"Failed to deserialize {col}, falling back to None"))for col in ("reasoning_details", "codex_reasoning_items", "codex_message_items") if row[col])- if row["tool_call_uids"] and (tool_uids := _uid_map(row["tool_call_uids"])):- msg[TOOL_CALL_UIDS] = tool_uidsif msg.get("tool_calls"):- # Provider ids repeat: this row's calls shadow an earlier occurrence's entries, and a- # row without a map (an older writer's) leaves its results unpaired rather than mispaired.- index_tool_call_uids(tool_uid_index, msg)+ unindexed_tool_owners.append(msg)elif row["role"] == "user":tool_uid_index.clear() # a result never pairs across a user turn- elif row["role"] == "tool":- # The stored uid, else the one its assistant row named (a result appended by an older build- # or a lone append): rows are read in id order, so the call always precedes its result.- tool_uid = row["tool_call_uid"] or resolve_tool_call_uid(tool_uid_index, row["tool_call_id"])- if tool_uid:+ unindexed_tool_owners.clear()+ elif row["role"] == "tool" and not row["tool_call_uid"] and row["tool_call_id"]:+ # No stored uid (a result appended by an older build or a lone append): the one its assistant+ # row named. Rows are read in id order, so the call always precedes its result. Provider ids+ # repeat: a later row's calls shadow an earlier occurrence's, and a row without a map (an older+ # writer's) leaves its results unpaired rather than mispaired.+ for owner in unindexed_tool_owners:+ index_tool_call_uids(tool_uid_index, owner)+ unindexed_tool_owners.clear()+ if tool_uid := resolve_tool_call_uid(tool_uid_index, row["tool_call_id"]):msg[TOOL_CALL_UID] = tool_uidif include_ancestors:skip, exact_clone_key = self._dedupe_replayed_user(messages, msg, exact_user_clones)diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.pyindex a0f4a7f023e..5b5cb6b2f2f 100644--- a/tests/hermes_state/test_message_uid.py+++ b/tests/hermes_state/test_message_uid.py@@ -245,14 +245,6 @@ class TestPersistedMergeWitness:assert restored[0]["_absorbed_message_uids"] == [prompt["message_uid"]]assert "_absorbed_message_uids" not in restored[1]- def test_a_survivor_inserted_as_a_fresh_row_carries_the_witness(self, db):- db.create_session("s", "cli")- composite = {"role": "user", "content": "a\n\nb", "message_uid": "a" * 32,- "_absorbed_message_uids": ["b" * 32, "c" * 32]}- db.append_messages_batch("s", [composite])- assert _absorbed(db, "s") == ['["%s", "%s"]' % ("b" * 32, "c" * 32)]- assert db.get_messages_as_conversation("s")[0]["_absorbed_message_uids"] == ["b" * 32, "c" * 32]-def test_tool_call_uids_are_minted_on_the_assistant_and_paired_onto_the_results(self, db):db.create_session("s", "cli")calls = [{"id": "call_1", "type": "function", "function": {"name": "t", "arguments": "{}"}},@@ -453,3 +445,29 @@ def test_a_branch_copy_writes_the_uids_its_live_history_keeps(tmp_path):assert history[0]["message_uid"] == "a" * 32 and UID_RE.match(history[1]["message_uid"])finally:db.close()+++def _call(cid):+ return {"id": cid, "type": "function", "function": {"name": "t", "arguments": "{}"}}+++def test_a_result_pairs_with_the_assistant_that_named_it_not_the_nearest_one(db):+ """Restore (results without a stored uid) and the flush walk both skip a nearer assistant that never+ named the result's call, and pair with the one that did."""+ from agent.message_metadata import tool_call_uid_from_history++ db.create_session("s", "cli")+ msgs = [{"role": "user", "content": "q"},+ {"role": "assistant", "content": "", "tool_calls": [_call("call_1")]},+ {"role": "assistant", "content": "", "tool_calls": [_call("call_2")]},+ {"role": "tool", "content": "r2", "tool_call_id": "call_2"},+ {"role": "tool", "content": "r1", "tool_call_id": "call_1"}]+ db.append_messages_batch("s", msgs)+ first, second = msgs[1]["_tool_call_uids"]["call_1"], msgs[2]["_tool_call_uids"]["call_2"]+ db._conn.execute("UPDATE messages SET tool_call_uid = NULL") # results written by an older build+ db._conn.commit()+ restored = [m for m in db.get_messages_as_conversation("s", repair_alternation=False) if m["role"] == "tool"]+ assert [m.get("_tool_call_uid") for m in restored] == [second, first]+ live = [{k: v for k, v in m.items() if k != "_tool_call_uid"} for m in msgs]+ owners: dict = {}+ assert [tool_call_uid_from_history(live, i, owners) for i in (3, 4)] == [second, first]