The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): archived rows stay out of the import's checkpoint pruning
John Paul Soliva0325349f96eb
diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 94245a85549..72a223a3041 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -512,9 +512,12 @@ class SessionMessagesMixin:row = self._read_one("SELECT role FROM messages WHERE id = ? AND session_id = ? AND active = 1", (int(row_id), session_id))return row[0] if row else None- def _insert_message_rows(self, conn, session_id: str, messages: List[Dict[str, Any]]) -> tuple[int, int]:+ def _insert_message_rows(self, conn, session_id: str, messages: List[Dict[str, Any]], *,+ prune_checkpoints: bool = True) -> tuple[int, int]:"""Insert *messages* as fresh active rows in the caller's txn -> ``(inserted, tool_call_count)``.- Never touches sessions.* counters (callers reconcile differently); reasoning kept for assistant rows."""+ Never touches sessions.* counters (callers reconcile differently); reasoning kept for assistant rows.+ A caller that re-archives some rows afterwards passes ``prune_checkpoints=False`` and prunes once they+ are archived again (:meth:`_prune_shadowed_checkpoints`)."""now_ts = time.time()inserted = tool_calls_total = 0for msg in messages:@@ -533,11 +536,16 @@ class SessionMessagesMixin:inserted += 1tool_calls_total += _tool_calls_count(tool_calls)now_ts = max(now_ts, message_timestamp) + 1e-6- carrier = _newest_checkpoint_carrier(messages, "codex_reasoning_items")- if carrier >= 0 and isinstance(messages[carrier].get("_row_id"), int):- self._drop_shadowed_checkpoint_rows(conn, session_id, messages[carrier]["_row_id"])+ if prune_checkpoints:+ self._prune_shadowed_checkpoints(conn, session_id, messages)return inserted, tool_calls_total+ def _prune_shadowed_checkpoints(self, conn, session_id: str, live_messages: List[Dict[str, Any]]) -> None:+ """Keep only the newest checkpoint among *live_messages* (inserted rows carrying ``_row_id``)."""+ carrier = _newest_checkpoint_carrier(live_messages, "codex_reasoning_items")+ if carrier >= 0 and isinstance(live_messages[carrier].get("_row_id"), int):+ self._drop_shadowed_checkpoint_rows(conn, session_id, live_messages[carrier]["_row_id"])+def _drop_shadowed_checkpoint_rows(self, conn, session_id: str, carrier_row_id: int) -> int:"""Rewrite older active assistant rows so only the row *carrier_row_id* keeps a ``type: "compaction"``checkpoint (durable twin of ``context_compressor.drop_shadowed_checkpoints``). Under native compactiondiff --git a/hermes_state_portability.py b/hermes_state_portability.pyindex c41fa9df980..1f86d6857c2 100644--- a/hermes_state_portability.py+++ b/hermes_state_portability.py@@ -545,7 +545,8 @@ class SessionPortabilityMixin:sanitized_messages = [{**msg, **{key: _json_value(msg.get(key)) for key in _IMPORT_MESSAGE_JSON_FIELDS}} for msg in messages]- total_messages, total_tool_calls = self._insert_message_rows(conn, session_id, sanitized_messages)+ total_messages, total_tool_calls = self._insert_message_rows(+ conn, session_id, sanitized_messages, prune_checkpoints=False)# A row exported archived (``include_inactive``) must stay archived: inserted live, compacted or# rewound turns would re-enter model context. Session counters count live rows only.archived = [msg for msg in sanitized_messages if "active" in msg and not msg["active"] and "_row_id" in msg]@@ -554,6 +555,11 @@ class SessionPortabilityMixin:[(1 if msg.get("compacted") else 0, msg["_row_id"]) for msg in archived])total_messages -= len(archived)total_tool_calls -= sum(_tool_calls_count(_parse_tool_calls(msg.get("tool_calls"))) for msg in archived)+ # Pruning keys on live rows, so it runs only now: while every row was still live, an archived row's+ # newer checkpoint would strip the newest live one, and archived rows keep theirs as in the donor.+ archived_ids = {id(msg) for msg in archived}+ self._prune_shadowed_checkpoints(conn, session_id,+ [msg for msg in sanitized_messages if id(msg) not in archived_ids])conn.execute("UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",(total_messages, total_tool_calls, session_id))diff --git a/tests/tui_gateway/test_stranded_session_adoption.py b/tests/tui_gateway/test_stranded_session_adoption.pyindex d4323322728..a3d0367668b 100644--- a/tests/tui_gateway/test_stranded_session_adoption.py+++ b/tests/tui_gateway/test_stranded_session_adoption.py@@ -454,3 +454,33 @@ def test_adoption_carries_compacted_history_before_retiring_the_donor(gateway):finally:pdb.close()++def _every_row(db, session_id):+ return [(m["role"], m["content"], m["active"], m["compacted"], m.get("codex_reasoning_items"))+ for m in db.get_messages(session_id, include_inactive=True)]+++def test_adoption_keeps_every_row_checkpoint_sidecar(stores):+ """Rows written before shadowed-checkpoint pruning (#102374) each still carry their own checkpoint.+ Archived rows must not take part in the import's live-row pruning: a newer rewound carrier would+ strip the newest LIVE checkpoint, and the retired donor is the only other copy."""+ default_db, profile_db = stores+ _seed_stranded(default_db, turns=0)+ for i in range(1, 4):+ default_db.append_message(STRANDED_ID, "user", f"question {i}")+ default_db.append_message(STRANDED_ID, "assistant", f"answer {i}", codex_reasoning_items=[+ {"type": "compaction", "encrypted_content": f"checkpoint {i}"}])+ rows = default_db.get_messages(STRANDED_ID)+ default_db._execute_write(lambda conn: (+ conn.executemany("UPDATE messages SET codex_reasoning_items = ? WHERE id = ?", [+ (f'[{{"type": "compaction", "encrypted_content": "checkpoint {i}"}}]', rows[2 * i - 1]["id"])+ for i in range(1, 4)]),+ conn.executemany("UPDATE messages SET active = 0, compacted = ? WHERE id = ?", [+ (1, rows[0]["id"]), (1, rows[1]["id"]), (0, rows[4]["id"]), (0, rows[5]["id"])])))+ donor_rows = _every_row(default_db, STRANDED_ID)+ assert [row[4] is not None for row in donor_rows] == [False, True] * 3++ result = profile_db.adopt_session_lineage_from(default_db, STRANDED_ID)++ assert result["donor_retired"] is True+ assert _every_row(profile_db, STRANDED_ID) == donor_rows