Skip to content

The agent that grows with you

refactor(sessions): one uid reader/stamper and one identity-field copier in message_metadata

kshitijk4poor95b2aea9e752
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index 0d3eaba3d17..6ce0071867f 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from time import time as wall_time
+from uuid import uuid4
from typing import Any, List, Mapping, MutableMapping, Optional, TypeVar
@@ -41,15 +42,42 @@ PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset(
) | REPAIR_BOOKKEEPING_FIELDS
-def _uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:
+def message_uid_or_none(msg: Mapping[str, Any]) -> Optional[str]:
+ """The dict's ``message_uid`` when it is a non-empty string, else ``None`` (never coerced: an int or a
+ blank would be a bug upstream of the write, not an identity)."""
uid = msg.get(MESSAGE_UID)
return uid if isinstance(uid, str) and uid else None
+def stamp_message_uid(msg: MutableMapping[str, Any]) -> str:
+ """The dict's ``message_uid``, minting one (``uuid4().hex``) when it carries none.
+
+ Minted ONCE per logical message, at its first insert, and stamped on the caller's dict so every later
+ insert of that dict (compaction generation, rotation handoff, replace) writes the same uid. Never
+ derived from content, timestamp or tool-call ids: two distinct messages may share all three.
+ """
+ uid = message_uid_or_none(msg)
+ if uid is None:
+ uid = msg[MESSAGE_UID] = uuid4().hex
+ return uid
+
+
def _absorbed_uids(msg: Mapping[str, Any]) -> List[str]:
return [u for u in (msg.get(ABSORBED_MESSAGE_UIDS) or ()) if isinstance(u, str) and u]
+_IDENTITY_FIELD_TYPES = ((MESSAGE_UID, str), (ABSORBED_MESSAGE_UIDS, list), (TOOL_CALL_UIDS, dict), (TOOL_CALL_UID, str))
+
+
+def copy_identity_fields(src: Mapping[str, Any], dst: MutableMapping[str, Any]) -> None:
+ """Copy the non-empty identity fields (uid, merge witness, tool-call uids) from *src* onto *dst*: the
+ live dict to its flush row, and the committed row back onto the live dict."""
+ for key, kind in _IDENTITY_FIELD_TYPES:
+ value = src.get(key)
+ if isinstance(value, kind) and value:
+ dst[key] = kind(value) if kind is not str else value
+
+
def record_absorbed_message(
survivor: MutableMapping[str, Any], dropped: Mapping[str, Any], *, dropped_leads: bool = False,
) -> None:
@@ -62,8 +90,8 @@ def record_absorbed_message(
A dict without a uid (unflushed, scaffolding, engine-authored) contributes nothing; an empty result
leaves the survivor untouched.
"""
- survivor_uid = _uid_or_none(survivor)
- dropped_uid = _uid_or_none(dropped)
+ survivor_uid = message_uid_or_none(survivor)
+ dropped_uid = message_uid_or_none(dropped)
if dropped_leads and dropped_uid:
survivor[MESSAGE_UID] = dropped_uid
ordered = _absorbed_uids(dropped) + ([survivor_uid] if survivor_uid else []) + _absorbed_uids(survivor)
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 3bbcc4f6b28..04913b06b2b 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -24,8 +24,8 @@ from agent.memory_manager import sanitize_context
from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
from agent.trajectory import save_trajectory as _save_trajectory_to_file
from agent.message_metadata import (
- ABSORBED_MESSAGE_UIDS, DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, MESSAGE_UID, REPAIR_BOOKKEEPING_FIELDS, TOOL_CALL_UID,
- TOOL_CALL_UIDS, tool_call_uid_from_history)
+ DB_ROW_SNAPSHOT, MERGED_TURN_PREFIX, REPAIR_BOOKKEEPING_FIELDS, TOOL_CALL_UID, copy_identity_fields,
+ tool_call_uid_from_history)
from agent.transcript_repair import sync_flushed_message_markers
@@ -238,16 +238,9 @@ def _db_flush_row(agent, msg: Dict, is_current_turn_user: bool) -> Dict[str, Any
}
if isinstance(msg.get("_row_id"), int):
row["_row_id"] = msg["_row_id"]
- if isinstance(msg.get(MESSAGE_UID), str) and msg[MESSAGE_UID]:
- row[MESSAGE_UID] = msg[MESSAGE_UID]
- if isinstance(msg.get(ABSORBED_MESSAGE_UIDS), list) and msg[ABSORBED_MESSAGE_UIDS]:
- # The merge witness rides on the survivor's row (an owned column: a row-addressed rewrite of the
- # survivor writes it too), so a restart sees which rows the composite folded.
- row[ABSORBED_MESSAGE_UIDS] = list(msg[ABSORBED_MESSAGE_UIDS])
- if isinstance(msg.get(TOOL_CALL_UIDS), dict) and msg[TOOL_CALL_UIDS]:
- row[TOOL_CALL_UIDS] = dict(msg[TOOL_CALL_UIDS])
- if isinstance(msg.get(TOOL_CALL_UID), str) and msg[TOOL_CALL_UID]:
- row[TOOL_CALL_UID] = msg[TOOL_CALL_UID]
+ # The merge witness rides on the survivor's row (an owned column: a row-addressed rewrite of the
+ # survivor writes it too), so a restart sees which rows the composite folded.
+ copy_identity_fields(msg, row)
if isinstance(msg.get(DB_ROW_SNAPSHOT), str):
row[DB_ROW_SNAPSHOT] = msg[DB_ROW_SNAPSHOT]
return row
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
index 3d60484821a..07de06ad3d3 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -10,22 +10,10 @@ from typing import Any, Callable, Dict, List, Mapping
from agent.context_compressor import _DB_PERSISTED_MARKER
from agent.message_metadata import (
- ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS)
+ CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,
+ copy_identity_fields)
from hermes_state_common import _id_chunks, _placeholders
-from hermes_state_messages import _MESSAGE_WRITE_COLUMNS
-
-
-def _json_map(text: Any) -> Dict[str, str]:
- """A stored ``{tool call id: uid}`` JSON object as a dict of non-empty strings (``{}`` on bad input)."""
- import json
-
- try:
- value = json.loads(text) if isinstance(text, str) else None
- except (TypeError, ValueError):
- value = None
- 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}
+from hermes_state_messages import _MESSAGE_WRITE_COLUMNS, _uid_map
# Durable payload columns a row-addressed rewrite may change: every INSERT column except row identity,
@@ -172,7 +160,7 @@ def resolve_and_repair_transcript_batch(
# carried (a restored dict without one, or a dict stamped before a rolled-back insert).
if final_row[MESSAGE_UID]:
msg[MESSAGE_UID] = final_row[MESSAGE_UID]
- if stored_tool_uids := _json_map(final_row["tool_call_uids"]):
+ if stored_tool_uids := _uid_map(final_row["tool_call_uids"]):
# Stored pairings win; pairings only the live list knows (an un-persisted merge's union) stay.
live_tool_uids = msg.get(TOOL_CALL_UIDS)
msg[TOOL_CALL_UIDS] = {**(live_tool_uids if isinstance(live_tool_uids, dict) else {}), **stored_tool_uids}
@@ -299,14 +287,7 @@ def sync_flushed_message_markers(batch_msgs: List[Dict[str, Any]], batch_rows: L
written[_DB_PERSISTED_MARKER] = True
if isinstance(row.get("_row_id"), int):
written["_row_id"] = row["_row_id"]
- if isinstance(row.get(MESSAGE_UID), str) and row[MESSAGE_UID]:
- written[MESSAGE_UID] = row[MESSAGE_UID]
- if isinstance(row.get(ABSORBED_MESSAGE_UIDS), list) and row[ABSORBED_MESSAGE_UIDS]:
- written[ABSORBED_MESSAGE_UIDS] = list(row[ABSORBED_MESSAGE_UIDS])
- if isinstance(row.get(TOOL_CALL_UIDS), dict) and row[TOOL_CALL_UIDS]:
- written[TOOL_CALL_UIDS] = dict(row[TOOL_CALL_UIDS])
- if isinstance(row.get(TOOL_CALL_UID), str) and row[TOOL_CALL_UID]:
- written[TOOL_CALL_UID] = row[TOOL_CALL_UID]
+ copy_identity_fields(row, written)
if isinstance(row.get("timestamp"), (int, float)):
written["timestamp"] = row["timestamp"]
if isinstance(row.get(DB_ROW_SNAPSHOT), str):
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index ace61671c0a..e31493b21c5 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -17,7 +17,7 @@ from agent.context_compressor import (
from agent.memory_manager import sanitize_context
from agent.message_metadata import (
ABSORBED_MESSAGE_UIDS, CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,
- index_tool_call_uids, resolve_tool_call_uid)
+ index_tool_call_uids, message_uid_or_none, resolve_tool_call_uid, stamp_message_uid)
from agent.message_sanitization import _sanitize_surrogates, coalesce_tool_call_id
from hermes_cli.timefmt import coerce_epoch
from hermes_state_common import (
@@ -94,13 +94,6 @@ def _coerce_timestamp(value: Any, default: float) -> float:
return 0.0 if result == 0.0 else result
-def _message_uid_or_none(msg: Dict[str, Any]) -> Optional[str]:
- """The dict's ``message_uid`` when it is a non-empty string, else ``None`` (never coerced: an int or a
- blank would be a bug upstream of the write, not an identity)."""
- uid = msg.get(MESSAGE_UID)
- return uid if isinstance(uid, str) and uid else None
-
-
def _uid_list(value: Any) -> List[str]:
"""Normalize a uid list (a live list, or the JSON text an export/import carries) to unique non-empty
strings in order; anything else is ``[]``."""
@@ -334,7 +327,7 @@ class SessionMessagesMixin:
1 if msg.get("observed") else 0, 1 if msg.get("_compressed_summary") else 0, 1,
_str_or_none(msg.get("api_content")), _str_or_none(msg.get("display_kind")),
display_metadata, self._display_identity(self._display_dedupe_key(identity_row)),
- _message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"),
+ message_uid_or_none(msg), _uid_list_json(msg, ABSORBED_MESSAGE_UIDS, "absorbed_message_uids"),
_tool_call_uids_json(msg), _tool_call_uid_or_none(msg))
@staticmethod
@@ -361,20 +354,6 @@ class SessionMessagesMixin:
if uid:
msg[TOOL_CALL_UID] = uid
- @staticmethod
- def _stamp_message_uid(msg: Dict[str, Any]) -> str:
- """The dict's ``message_uid``, minting one (``uuid4().hex``) when it carries none.
-
- Minted ONCE per logical message, at its first insert, and stamped on the caller's dict so every
- later insert of that dict (compaction generation, rotation handoff, replace) writes the same uid.
- Never derived from content, timestamp or tool-call ids: two distinct messages may share all three.
- """
- uid = _message_uid_or_none(msg)
- if uid is None:
- uid = uuid.uuid4().hex
- msg[MESSAGE_UID] = uid
- return uid
-
def _serialized_message_row(
self, session_id: str, msg: Dict[str, Any], message_timestamp: float
) -> Dict[str, Any]:
@@ -467,7 +446,7 @@ class SessionMessagesMixin:
msg["display_metadata"] = self._encode_display_metadata(display_metadata)
tool_calls = _parse_tool_calls(tool_calls)
message_timestamp = _coerce_timestamp(timestamp, time.time())
- self._stamp_message_uid(msg) # a fresh occurrence: mint its durable id
+ stamp_message_uid(msg) # a fresh occurrence: mint its durable id
self._stamp_tool_call_uids(msg, tool_calls, {})
params = self._message_row_params(
session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=True)
@@ -493,7 +472,7 @@ class SessionMessagesMixin:
msg = {"content": content,
"display_kind": "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete",
"display_metadata": metadata}
- self._stamp_message_uid(msg) # a fresh occurrence: mint its durable id
+ stamp_message_uid(msg) # a fresh occurrence: mint its durable id
params = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)
def _do(conn):
@@ -793,7 +772,7 @@ class SessionMessagesMixin:
# The durable per-message id: kept when the dict carries one (a copy of an already-stored
# message), minted and stamped on the dict otherwise. Stamped BEFORE the bind so the row and
# the live dict never disagree. Tool calls get their per-occurrence ids the same way.
- self._stamp_message_uid(msg)
+ stamp_message_uid(msg)
self._stamp_tool_call_uids(msg, tool_calls, batch_tool_index)
cur = conn.execute(_INSERT_MESSAGE_SQL, self._message_row_params(
session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=role == "assistant"))
@@ -1889,7 +1868,7 @@ class SessionMessagesMixin:
if replacement is not None:
self._insert_message_rows(conn, session_id, [replacement])
replacement_message_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
- replacement_message_uid = _message_uid_or_none(replacement) # stamped by the insert
+ replacement_message_uid = message_uid_or_none(replacement) # stamped by the insert
conn.execute(
"UPDATE sessions SET rewind_count = COALESCE(rewind_count, 0) + 1 WHERE id = ?", (session_id,))
message_count, tool_call_count = self._active_transcript_counts(conn, session_id)