Skip to content

The agent that grows with you

Merge branch 'simp/r2-state-b' into simp/integration2

Teknium7d0f4ce3aa79
diff --cc hermes_state_messages.py
index 2a3f57a1f75,8e6d75f9ba0..161d5a520ed
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@@ -126,15 -139,8 +139,14 @@@ class SessionMessagesMixin
def _encode_content(cls, content: Any) -> Any:
"""Serialize list/dict content (multimodal parts) as a sentinel-prefixed JSON
string; sqlite3 can only bind str/bytes/int/float/None. Lone surrogates are
- scrubbed from text so persistence never fails. Paired with :meth:`_decode_content`.
- """
+ scrubbed from text so persistence never fails. Paired with :meth:`_decode_content`."""
if isinstance(content, str):
+ # Lone UTF-16 surrogates arrive in tool results scraped from the web. The
+ # upstream sanitizer only cleans the api_messages copy and the recovery
+ # sanitizer only runs after the API call raises (it no longer does), so the
+ # canonical history keeps them and this write is where they land. Left raw,
+ # sqlite3 raises UnicodeEncodeError, the flush is abandoned, and the session
+ # silently stops persisting for the rest of its life.
return _sanitize_surrogates(content)
if content is None or isinstance(content, (bytes, int, float)):
return content
@@@ -1162,16 -1050,10 +1059,13 @@@
content = self._decode_content(row["content"])
if row["role"] in {"user", "assistant"} and isinstance(content, str):
content = sanitize_context(content).strip()
- msg = {"role": row["role"], "content": content}
+ # Underscore-prefixed like ``_row_id``: every transport strips it before the
+ # wire, and compression's assembly copies deliberately strip it so rotated
+ # child handoffs still flush (see _fresh_compaction_message_copy).
- msg[_DB_PERSISTED_MARKER_KEY] = True
+ msg = {"role": row["role"], "content": content, _DB_PERSISTED_MARKER_KEY: True}
if include_row_ids and row["id"] is not None:
msg["_row_id"] = row["id"]
- for col in ("api_content", "display_kind"):
- if row[col]:
- msg[col] = row[col]
+ msg.update((col, row[col]) for col in _VERBATIM_COLS if row[col])
if row["display_metadata"]:
decoded = self._decode_display_metadata(row["display_metadata"])
if decoded is not None:
@@@ -1529,17 -1361,13 +1373,14 @@@
def message_count(self, session_id: str = None) -> int:
"""Count messages, optionally for a specific session."""
- with self._read_ctx() as conn:
- if session_id:
- cursor = conn.execute("SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,))
- else:
- cursor = conn.execute("SELECT COUNT(*) FROM messages")
- return cursor.fetchone()[0]
+ if session_id:
+ return self._read_one("SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,))[0]
+ return self._read_one("SELECT COUNT(*) FROM messages")[0]
def has_platform_message_id(self, session_id: str, platform_message_id: str) -> bool:
- """True when a message with *platform_message_id* exists (partial index lookup;
- the gateway's transient-failure dedupe guard)."""
+ """True when a message with *platform_message_id* exists (uses the
+ idx_messages_platform_msg_id partial index; the gateway's transient-failure
+ dedupe guard)."""
return self._read_one(
"SELECT 1 FROM messages WHERE session_id = ? AND platform_message_id = ? LIMIT 1",
(session_id, platform_message_id),
@@@ -1579,20 -1400,12 +1414,17 @@@
return bool(session and self._is_explicit_fork_child_row(session))
def latest_conversation_boundary(self, session_key: str, source: str) -> Optional[int]:
- """How many conversation boundaries (``_RESET_END_REASONS`` ends) this routing
- peer has crossed, or ``None`` when never reset.
-
- The peer is ``(session_key, source)`` — the identity recovery uses — never the
- key alone (an API caller may legally reuse a Telegram row's key). Read from
+ """Conversation boundaries (``_RESET_END_REASONS`` ends) this routing peer has
+ crossed, or ``None`` when never reset. The peer is ``(session_key, source)`` — never
+ the key alone (an API caller may reuse a Telegram row's key). Read from
- ``conversation_generations``, not an aggregate over session rows (deletes/prunes
- would re-emit a retired pair); rows are never GC'd (dropping one would re-issue
- generation 1 — the ABA this counter prevents)."""
+ ``conversation_generations`` (advanced inside each boundary's txn), not an
- aggregate over session rows: deletes/prunes would let an aggregate re-emit a
- retired pair. Rows are never garbage-collected, by design (dropping one would
- re-issue generation 1 — the ABA this counter prevents). Wall-clock-free, so a
- backwards NTP correction cannot reorder it. DBs upgraded mid-conversation start
- at no generation and take their first from the next boundary written; a
- conversation that reset before the upgrade shares its predecessor's scope once
- (costs a warm prompt-cache bucket, never crosses an identity).
- """
++ aggregate over session rows (deletes/prunes would re-emit a retired pair); rows are
++ never GC'd (dropping one would re-issue generation 1 — the ABA this counter
++ prevents). Wall-clock-free, so a backwards NTP correction cannot reorder it. DBs
++ upgraded mid-conversation start at no generation and take their first from the
++ next boundary written; a conversation that reset before the upgrade shares its
++ predecessor's scope once (costs a warm prompt-cache bucket, never crosses an
++ identity)."""
if not session_key or not source:
return None
row = self._read_one(