Skip to content

The agent that grows with you

fix(sessions): an assistant fold keeps every occurrence uid of a reused provider id

kshitijk4poord9808867c71b
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index d72624d86dd..724f2b51409 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -19,7 +19,7 @@ from hermes_cli.timeouts import get_provider_request_timeout
from agent.message_sanitization import (
_FULL_ARGS_LOG_BOUND, coalesce_tool_call_id, coerce_tool_name, tool_call_id_variants, tool_result_id_variants
)
-from agent.message_metadata import TOOL_CALL_UIDS, record_absorbed_message
+from agent.message_metadata import TOOL_CALL_UIDS, merge_tool_call_uids, record_absorbed_message
from agent.prompt_builder import STEER_DISPLAY_KIND, steer_user_row
from agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_result_message
from agent.think_scrubber import THINK_TAG_NAMES
@@ -392,7 +392,7 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
prev["tool_calls"] = prev_calls + new_calls
# The absorbed turn's calls keep the per-occurrence ids they were persisted with.
if isinstance(msg.get(TOOL_CALL_UIDS), dict) and msg[TOOL_CALL_UIDS]:
- prev[TOOL_CALL_UIDS] = {**(prev.get(TOOL_CALL_UIDS) or {}), **msg[TOOL_CALL_UIDS]}
+ prev[TOOL_CALL_UIDS] = merge_tool_call_uids(prev.get(TOOL_CALL_UIDS) or {}, msg[TOOL_CALL_UIDS])
calls_changed = True
elif prev_calls:
prev["tool_calls"] = prev_calls
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index 4e0796abaea..e7a16936827 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -128,11 +128,26 @@ def _named_tool_call_variants(assistant: Any) -> List[str]:
return [variant for tc in assistant.get("tool_calls") or () for variant in tool_call_id_variants(tc)]
+def merge_tool_call_uids(into: Mapping[str, Any], extra: Mapping[str, Any]) -> dict:
+ """Union two ``_tool_call_uids`` maps without losing an occurrence. Folding two assistant turns that
+ reuse a provider id (llama.cpp-style constant ids) leaves both calls in ``tool_calls``; the id then maps
+ to every occurrence's uid, in call order, as a list. Provider ids themselves are never rewritten."""
+ merged = dict(into)
+ for call_id, uid in extra.items():
+ merged[call_id] = _uid_occurrences(merged[call_id]) + _uid_occurrences(uid) if call_id in merged else uid
+ return merged
+
+
+def _uid_occurrences(value: Any) -> list:
+ return list(value) if isinstance(value, list) else [value]
+
+
def index_tool_call_uids(index: MutableMapping[str, str], assistant: Any) -> None:
"""Register an assistant dict's ``_tool_call_uids`` under every pairing-id variant of its tool calls, so a
later tool-result row can be resolved by any spelling of its ``tool_call_id``. Provider ids repeat, so
every id this assistant names first shadows an earlier occurrence's entry: a result pairs with the
- NEAREST preceding call, and a call without a uid (a legacy row) pairs its result with nothing."""
+ NEAREST preceding call, and a call without a uid (a legacy row) pairs its result with nothing. A
+ provider id repeated inside one row (two folded turns) maps each call to its own occurrence's uid."""
from agent.message_sanitization import coalesce_tool_call_id, tool_call_id_variants
for variant in _named_tool_call_variants(assistant):
@@ -140,8 +155,13 @@ def index_tool_call_uids(index: MutableMapping[str, str], assistant: Any) -> Non
uids = assistant.get(TOOL_CALL_UIDS) if isinstance(assistant, dict) else None
if not isinstance(uids, dict) or not uids:
return
+ occurrence: dict = {} # provider id -> calls seen so far: a list value holds one uid per occurrence
for tc in assistant.get("tool_calls") or ():
- uid = uids.get(coalesce_tool_call_id(tc))
+ call_id = coalesce_tool_call_id(tc)
+ uid = uids.get(call_id)
+ if isinstance(uid, list):
+ nth = occurrence[call_id] = occurrence.get(call_id, -1) + 1
+ uid = uid[nth] if nth < len(uid) else None
if isinstance(uid, str) and uid:
for variant in tool_call_id_variants(tc):
index[variant] = uid
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 2d16b784e7e..68dacc176ef 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -112,13 +112,15 @@ def _uid_list_json(msg: Dict[str, Any], live_key: str, column: str) -> Optional[
def _uid_map(value: Any) -> Dict[str, str]:
- """Normalize a ``{tool call id: uid}`` map (a live dict, or the JSON text an export/import carries) to
- non-empty string pairs; anything else is ``{}``."""
+ """Normalize a ``{tool call id: uid}`` map (a live dict, or the JSON text an export/import carries): a
+ non-empty string uid, or a list of them for a provider id repeated inside one row (one per occurrence,
+ see ``merge_tool_call_uids``); anything else is dropped, and a non-map is ``{}``."""
if isinstance(value, str):
value = _json_or(value, {}, "Failed to deserialize a tool-call uid map, falling back to {}")
if not isinstance(value, dict):
return {}
- return {k: v for k, v in value.items() if isinstance(k, str) and k and isinstance(v, str) and v}
+ return {k: v for k, v in value.items() if isinstance(k, str) and k and (
+ (isinstance(v, str) and v) or (isinstance(v, list) and v and all(isinstance(u, str) and u for u in v)))}
def _restore_identity_columns(row: Any, msg: Dict[str, Any]) -> None:
diff --git a/tests/agent/test_context_engine_message_uid.py b/tests/agent/test_context_engine_message_uid.py
index 11dfeda5b85..411b898e095 100644
--- a/tests/agent/test_context_engine_message_uid.py
+++ b/tests/agent/test_context_engine_message_uid.py
@@ -300,6 +300,57 @@ def test_assistant_merge_keeps_the_absorbed_turns_tool_call_uids():
assert first["_tool_call_uids"] == {"call_1": "1" * UID_LEN, "call_2": "2" * UID_LEN}
+def _reused_call(content, occurrence_uid=None):
+ msg = {"role": "assistant", "content": content,
+ "tool_calls": [{"id": "call_x", "type": "function", "function": {"name": "t", "arguments": "{}"}}]}
+ if occurrence_uid:
+ msg["_tool_call_uids"] = {"call_x": occurrence_uid}
+ return msg
+
+
+def test_assistant_merge_keeps_every_occurrence_of_a_reused_provider_id():
+ """Two folded turns that reuse a provider id (llama.cpp) both keep their call AND their occurrence uid;
+ the ids on the wire are untouched, and a following result pairs with the nearest (later) call."""
+ from agent.agent_runtime_helpers import _merge_consecutive_assistants
+ from agent.message_metadata import index_tool_call_uids, resolve_tool_call_uid
+
+ first, second = _reused_call("", "1" * UID_LEN), _reused_call("", "2" * UID_LEN)
+ merged, repairs = _merge_consecutive_assistants([first, second])
+ assert repairs == 1 and merged == [first]
+ assert [tc["id"] for tc in first["tool_calls"]] == ["call_x", "call_x"]
+ assert first["_tool_call_uids"] == {"call_x": ["1" * UID_LEN, "2" * UID_LEN]}
+ index: dict = {}
+ index_tool_call_uids(index, first)
+ assert resolve_tool_call_uid(index, "call_x") == "2" * UID_LEN
+
+
+def test_a_reused_id_merge_survives_rewrite_and_restore(db):
+ """The per-occurrence map a fold produces is what the survivor's rewrite persists and a restore returns;
+ the result keeps the uid of the call it answered."""
+ from agent.agent_runtime_helpers import repair_message_sequence
+
+ sid = "20260928_120600_reused"
+ db.create_session(sid, "cli", model="test/model")
+ agent = _make_agent(db, sid)
+ agent._session_db_created = True
+ first, second = _reused_call("checking"), _reused_call("")
+ result = {"role": "tool", "content": "r", "tool_call_id": "call_x", "tool_name": "t"}
+ messages = [{"role": "user", "content": "q"}, first, second, result]
+ agent._persist_user_message_idx = 0
+ agent._persist_session(messages, conversation_history=None)
+ occurrences = [first["_tool_call_uids"]["call_x"], second["_tool_call_uids"]["call_x"]]
+ assert len(set(occurrences)) == 2 and result["_tool_call_uid"] == occurrences[1]
+
+ repair_message_sequence(agent, messages)
+ assert first["_tool_call_uids"] == {"call_x": occurrences}
+ agent._persist_session(messages, conversation_history=None)
+
+ again = db.get_messages_as_conversation(sid, repair_alternation=False)
+ stored = next(m for m in again if m["role"] == "assistant" and m.get("tool_calls"))
+ assert stored["_tool_call_uids"] == {"call_x": occurrences}
+ assert next(m for m in again if m["role"] == "tool")["_tool_call_uid"] == occurrences[1]
+
+
def test_a_select_context_selection_is_stripped_before_the_provider():
"""The request copy is stripped BEFORE ``select_context``; an engine that hands back the
``conversation_messages`` clones must not put the ids back on the wire."""
diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.md
index 6f429606ed2..349bbec6474 100644
--- a/website/docs/developer-guide/context-engine-plugin.md
+++ b/website/docs/developer-guide/context-engine-plugin.md
@@ -193,7 +193,9 @@ What the host guarantees:
(Hermes mints deterministic `call_<12hex>` ids for identical calls, and models
reuse ids), so an assistant message carries `_tool_call_uids`, a
`{tool_call_id: uid}` map for its `tool_calls`, and each tool-result message
- carries the matching `_tool_call_uid`. The provider-facing `id` inside
+ carries the matching `_tool_call_uid`. When a fold leaves one message with two
+ calls that share a provider id, that id maps to a list of uids, one per
+ occurrence in `tool_calls` order. The provider-facing `id` inside
`tool_calls` is untouched. Both are minted at the assistant row's first
insert, paired onto the result when it is flushed (same batch, or from the
live list when the result lands in a later flush) and on restore (from the
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 26622383c27..ed421f9ba48 100644
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@ -245,7 +245,7 @@ Notes:
- Timestamps are Unix epoch floats (`time.time()`)
- `message_uid` is the durable per-message id (32 hex, `uuid4().hex`): minted once at a row's first insert and copied by every clone (in-place compaction generations, rotation children, concurrent-tail clones, `replace_messages` re-issues, export/import), so one logical message keeps one uid while its physical `id` changes. Row-addressed rewrites leave it alone. It is restored on every projection (`get_messages_as_conversation` sets it unconditionally; `_row_id` stays opt-in) and stripped from provider requests. Context engines key their own per-message state on it — see [Context Engine Plugins](./context-engine-plugin.md#stable-message-identity-message_uid).
- `absorbed_message_uids` is the merge witness: a JSON list of the `message_uid`s the host folded into this row (alternation repair's user and assistant merges, the compressor's in-flight restatement and anchor folds, micro-compaction's adjacent-user merge; the composite keeps the first constituent's uid). Written when the survivor is flushed, rewritten with it, restored as the live `_absorbed_message_uids`, `NULL` on rows that absorbed nothing.
-- `tool_call_uids` (assistant rows) is a JSON `{tool_call_id: uid}` map giving each entry of `tool_calls` a per-occurrence id, because provider tool-call ids repeat; `tool_call_uid` (tool rows) is the matching value for the result. The `tool_calls` JSON itself is never modified. Minted at the assistant row's first insert, paired onto the result at flush or, when the column is `NULL`, derived on restore from the preceding assistant row; restored as the live `_tool_call_uids` / `_tool_call_uid`.
+- `tool_call_uids` (assistant rows) is a JSON `{tool_call_id: uid}` map giving each entry of `tool_calls` a per-occurrence id, because provider tool-call ids repeat (an id repeated inside one row, after two assistant turns are folded, maps to a list of uids in call order); `tool_call_uid` (tool rows) is the matching value for the result. The `tool_calls` JSON itself is never modified. Minted at the assistant row's first insert, paired onto the result at flush or, when the column is `NULL`, derived on restore from the preceding assistant row; restored as the live `_tool_call_uids` / `_tool_call_uid`.
### FTS5 Full-Text Search