The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state,codex): a dedupe claim never drops a different message; a cut codex stream retries
Tekniuma995b69417ee
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.pyindex a11956636fb..cfc3b9c64d3 100644--- a/agent/codex_runtime.py+++ b/agent/codex_runtime.py@@ -903,6 +903,9 @@ class _CodexResponseAssembler:# first-observed (sequence, output_index) per announced item id so a later .done keeps its announced position.self.pending_function_calls: dict[str, dict[str, Any]] = {}self.announced_output_order: dict[str, tuple] = {}+ # Phase per announced message item id: a delta that names its item keeps that item's phase even after a+ # later item (a function call) was announced, so commentary is never fused into the answer text.+ self.message_phases: dict[str, str | None] = {}def _safe(self, cb: Callable | None, label: str, *args: Any) -> None:_call_guarded(cb, f"Codex stream {label} raised", args=args)@@ -918,6 +921,8 @@ class _CodexResponseAssembler:# Record first-observed ordering for EVERY announced item; .done must reuse it or a mixed# announced/pending stream without output_index values reorders the calls.item_id = str(_event_field(item, "id", ""))+ if item_id and item_type == "message":+ self.message_phases[item_id] = self.active_message_phaseif item_id and item_id not in self.announced_output_order:self.announced_output_order[item_id] = (self.next_output_sequence, _event_field(event, "output_index"))self.next_output_sequence += 1@@ -936,12 +941,13 @@ class _CodexResponseAssembler:return# Harmony commentary/analysis text is mid-turn narration, never the final answer: route to the# reasoning callback, keep only the item for replay.- if self.active_message_phase == "commentary":+ phase = self.message_phases.get(str(_event_field(event, "item_id", "") or ""), self.active_message_phase)+ if phase == "commentary":self.commentary_text_deltas.append(delta_text)# Legacy fallback when no first-class commentary consumer is installed.if self.on_commentary_message is None:self._safe(self.on_reasoning_delta, "on_reasoning_delta", delta_text)- elif self.active_message_phase == "analysis":+ elif phase == "analysis":self._safe(self.on_reasoning_delta, "on_reasoning_delta", delta_text)else:self.text_deltas.append(delta_text)@@ -1109,9 +1115,11 @@ class _CodexResponseAssembler:# Plain text deltas with no output at all: synthesize one message item. Beside tool calls and commentary# items, only an ANNOUNCED answer message whose done event never came is recovered, or the text said around# a call is dropped from the turn (#143893); bare output_text beside commentary stays narration (length).+ # The recovery needs a terminal frame: a stream cut mid-turn (no terminal, a call still pending) must raise+ # below and retry, never end the turn on the cut-off sentence with the call silently lost.if self.text_deltas and ((not output and not self.has_tool_calls)- or (self.saw_answer_item_added and not any(+ or (self.saw_terminal and self.saw_answer_item_added and not any(_event_field(item, "type", "") == "message"and _message_phase(item) not in ("commentary", "analysis") for item in output))):content = [SimpleNamespace(type="output_text", text="".join(self.text_deltas))]diff --git a/agent/transcript_repair.py b/agent/transcript_repair.pyindex a9f9a19333b..dbaf76ef4ef 100644--- a/agent/transcript_repair.py+++ b/agent/transcript_repair.py@@ -109,8 +109,8 @@ def _active_logical_message_row(def _active_uid_dedupe(conn: sqlite3.Connection, session_id: str, messages: list[dict[str, Any]]-) -> set[str]:- """ACTIVE durable uids among *messages*' restored, no-snapshot, no-``_row_id`` rows — the re-insert guard.+) -> dict[str, list[sqlite3.Row]]:+ """ACTIVE durable rows by uid among *messages*' restored, no-snapshot, no-``_row_id`` rows — the re-insert guard.Only a row the agent flush marked ``RESTORED_FROM_STORE`` (it saw that uid durable in this session) is acandidate: a copied uid alone is never proof, so a fresh identical message always inserts. A dict rebuilt@@ -132,21 +132,30 @@ def _active_uid_dedupe(and not isinstance(msg.get(DB_ROW_SNAPSHOT), str)and (uid := message_uid_or_none(msg))})- durable: set[str] = set()- if not candidate_uids:- return durable+ durable: dict[str, list[sqlite3.Row]] = {}for chunk in _id_chunks(candidate_uids):- durable.update(- row["message_uid"]- for row in conn.execute(- f"SELECT DISTINCT message_uid FROM messages "- f"WHERE session_id = ? AND active = 1 AND message_uid IN ({_placeholders(chunk)})",- (session_id, *chunk),- ).fetchall()- )+ for row in conn.execute(+ f"SELECT * FROM messages WHERE session_id = ? AND active = 1 AND message_uid IN ({_placeholders(chunk)})",+ (session_id, *chunk),+ ).fetchall():+ durable.setdefault(row["message_uid"], []).append(row)return durable+def _same_as_stored(+ msg: dict[str, Any], rows: list[sqlite3.Row],+ serialize_message_fn: Callable[[dict[str, Any], float], Mapping[str, Any]],+) -> bool:+ """*msg* serializes to the owned columns of one of its uid's active *rows*: the re-handed copy, not an edit."""+ for row in rows:+ serialized = serialize_message_fn(msg, float(row["timestamp"]))+ if serialized["token_count"] is None: # a restored dict never decodes token_count: unknown, not NULL+ serialized = {**serialized, "token_count": row["token_count"]}+ if all(row[column] == serialized[column] for column in _OWNED_COLUMNS):+ return True+ return False++def resolve_and_repair_transcript_batch(conn: sqlite3.Connection,session_id: str,@@ -162,8 +171,8 @@ def resolve_and_repair_transcript_batch(its physical ``_row_id``, the pair (logical ``message_uid``, stored-row snapshot) recovers the newestactive generation without matching mutable payload. Watermark-compaction clones are matched by theircopied payload identity, not timestamp alone. Legacy blank assistant rows retain the narrow interrupted-- stream content repair. A snapshot-less restored dict whose uid is already an ACTIVE durable row is the- same logical message re-handed to the flush — stamped durable and skipped, never re-INSERTed. Returns+ stream content repair. A snapshot-less restored dict whose uid is already an ACTIVE durable row with the+ same payload is that message re-handed to the flush — stamped durable and skipped, never re-INSERTed. Returnsonly rows that need fresh inserts."""inserted_rows: list[dict[str, Any]] = []@@ -183,12 +192,14 @@ def resolve_and_repair_transcript_batch(from agent.session_persistence import _PERSIST_AFTER_ADMISSION_INTERRUPTif (isinstance(msg, dict)- and message_uid_or_none(msg) in durable_uids+ and (stored := durable_uids.get(message_uid_or_none(msg) or ""))and not msg.get(_PERSIST_AFTER_ADMISSION_INTERRUPT)+ and _same_as_stored(msg, stored, serialize_message_fn)):# Restored logical message, no row address and no CAS version (the wire strip removes- # every underscore-prefixed field): its uid already names an ACTIVE durable row, so- # this is the re-insert defect, not a new message. Stamp durable; the row-addressed+ # every underscore-prefixed field): its uid already names an ACTIVE durable row holding+ # the same payload, so this is the re-insert defect, not a new message. Stamp durable; a+ # restored dict edited since (other content) inserts as before, and the row-addressed# repair above keeps snapshot-carrying rewrites live.msg[_DB_PERSISTED_MARKER] = Truecontinuediff --git a/hermes_state_coverage.py b/hermes_state_coverage.pyindex f5605b7d682..b4916b68dd2 100644--- a/hermes_state_coverage.py+++ b/hermes_state_coverage.py@@ -20,23 +20,28 @@ class SessionCoverageMixin:def _carried_tail_ids(self, conn, tail_ids: list[int], compacted_messages: list[dict[str, Any]],- ) -> dict[int, int]:- """Rows of *tail_ids* that *compacted_messages* already carry -> ``{row id: index of the carrying dict}``.+ ) -> tuple[dict[int, int], set[int]]:+ """Rows of *tail_ids* that *compacted_messages* already carry -> ``({row id: carrying dict index}, weak)``.A row above the watermark is normally a concurrent append the summary never saw, so the commitclones it after the compacted set. A row the compressor ALSO held (flushed after the watermarkwas read, or left unnamed so coverage fell back to the watermark) is already in the compactedset as a carried copy; cloning it too stores the message twice, with a fresh id and timestamp- each (#137197). A dict names its row by ``_row_id``, by ``message_uid``, by identity plus- timestamp, or, carrying none of those, by identity alone. Each dict claims at most one row and- each row is claimed once, so a second row with the same text (another surface's append) keeps- its clone.+ each (#137197). A claim never drops a different message, so each proof is checked against the+ row: a dict that names a row by ``_row_id`` claims only that row; a ``message_uid`` match also needs+ the same identity (a same-uid row with other content is another version, kept); identity plus+ timestamp, or identity alone for a dict carrying no stamps at all, never claims a row whose uid+ differs from the dict's. Each dict claims at most one row and each row is claimed once.++ ``weak`` holds the rows claimed by identity alone (with or without a timestamp): two surfaces can+ store the same text, so the caller archives those as compacted history, never rewinds them out of+ display, and a wrong claim stays visible."""if not tail_ids or not compacted_messages:- return {}+ return {}, set()by_row: dict[int, tuple[int, tuple[Any, ...]]] = {}- by_uid: dict[str, int] = {}- by_key: dict[tuple[Any, ...], int] = {}+ by_uid: dict[str, tuple[int, tuple[Any, ...]]] = {}+ by_key: dict[tuple[Any, ...], tuple[int, Optional[str]]] = {}bare: dict[tuple[Any, ...], list[int]] = {}for index, message in enumerate(compacted_messages):if not isinstance(message, dict):@@ -48,40 +53,48 @@ class SessionCoverageMixin:if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0:# Authoritative only while the stored identity still matches (a stale stamp names another row).by_row.setdefault(row_id, (index, identity))- else:- row_id = None+ continueuid = message_uid_or_none(message)if uid is not None:- by_uid.setdefault(uid, index)+ by_uid.setdefault(uid, (index, identity))timestamp = coerce_epoch(message.get("timestamp"), field="message timestamp")if timestamp is not None:- by_key.setdefault((*identity, timestamp), index)- elif row_id is None and uid is None:+ by_key.setdefault((*identity, timestamp), (index, uid))+ elif uid is None:bare.setdefault(identity, []).append(index)carried: dict[int, int] = {}+ weak: set[int] = set()claimed: set[int] = set()for row in conn.execute(f"SELECT id, role, content, tool_call_id, tool_calls, timestamp, {MESSAGE_UID} FROM messages "f"WHERE id IN ({_placeholders(tail_ids)}) ORDER BY id", tail_ids,).fetchall():+ row_id, row_uid = int(row["id"]), row[MESSAGE_UID] or Noneidentity = self._row_identity(row["role"], self._decode_content(row["content"]), row["tool_call_id"],_parse_tool_calls(row["tool_calls"]))- index = None- if (named := by_row.get(int(row["id"]))) is not None and named[1] == identity:- index = named[0]- if index is None and row[MESSAGE_UID]:- index = by_uid.get(row[MESSAGE_UID])- if index is None:- timestamp = coerce_epoch(row["timestamp"], field="message timestamp")- if timestamp is not None:- index = by_key.get((*identity, timestamp))- if index is None and (queue := bare.get(identity)):- index = queue.pop(0)+ index, strong = self._claim_tail_row(row, row_id, row_uid, identity, by_row, by_uid, by_key, bare)if index is not None and index not in claimed:claimed.add(index)- carried[int(row["id"])] = index- return carried+ carried[row_id] = index+ if not strong:+ weak.add(row_id)+ return carried, weak++ @staticmethod+ def _claim_tail_row(row, row_id, row_uid, identity, by_row, by_uid, by_key, bare) -> tuple[Optional[int], bool]:+ """The carrying dict index for one tail row and whether the proof names that row (``_row_id`` / uid)."""+ if (named := by_row.get(row_id)) is not None and named[1] == identity:+ return named[0], True+ if row_uid is not None and (by_id := by_uid.get(row_uid)) is not None and by_id[1] == identity:+ return by_id[0], True+ timestamp = coerce_epoch(row["timestamp"], field="message timestamp")+ if timestamp is not None and (keyed := by_key.get((*identity, timestamp))) is not None:+ if keyed[1] is None: # a dict uid equal to the row's already matched above+ return keyed[0], False+ if queue := bare.get(identity):+ return queue.pop(0), False+ return None, False@staticmethoddef _carried_tail_slots(carried: dict[int, int], compacted_count: int, tail_count: int) -> int:diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 220bbeabb06..2543495c628 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -867,13 +867,14 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):unseen = [row_id for row_id in active_ids if row_id not in covered_set]covered_active = [row_id for row_id in active_ids if row_id in covered_set]# An unseen row the compacted set already carries is superseded by that copy, not cloned (#137197).- carried_unseen = self._carried_tail_ids(conn, unseen, compacted_messages)+ carried_unseen, weak_claims = self._carried_tail_ids(conn, unseen, compacted_messages)clone_ids = [row_id for row_id in unseen if row_id not in carried_unseen]tail_below = tail_count - self._carried_tail_slots(carried_unseen, len(compacted_messages), tail_count)rewind_ids = list(carried_ids)if tail_below > 0:rewind_ids += self._tail_originals(covered_active, tail_below, merged_away)- rewind_ids += unseen+ # A row claimed by identity alone is archived as compacted history, never rewound out of display.+ rewind_ids += [row_id for row_id in unseen if row_id not in weak_claims]rewind_ids = list(dict.fromkeys(rewind_ids))if rewind_ids:placeholders = _placeholders(rewind_ids)@@ -990,7 +991,7 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):(session_id, int(watermark))).fetchall()]# A concurrent-tail row the compacted set already carries is superseded by that copy, not# cloned beside it (#137197); its carried dict then has no original below the watermark.- carried_tail = self._carried_tail_ids(conn, tail_ids, compacted_messages)+ carried_tail, weak_claims = self._carried_tail_ids(conn, tail_ids, compacted_messages)clone_ids = [row_id for row_id in tail_ids if row_id not in carried_tail]_ids, tail_tool_calls = ([], 0) if not clone_ids else self._tail_rows_after_watermark(conn, f"SELECT id, tool_calls FROM messages WHERE id IN ({_placeholders(clone_ids)}) ORDER BY id",@@ -1007,7 +1008,8 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):"ORDER BY id DESC LIMIT ?",(session_id, *((int(watermark),) if bound else ()),int(tail_below) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]- rewind_ids += tail_ids+ # A row claimed by identity alone is archived as compacted history, never rewound out of display.+ rewind_ids += [row_id for row_id in tail_ids if row_id not in weak_claims]rewind_ids = list(dict.fromkeys(rewind_ids))if rewind_ids:placeholders = _placeholders(rewind_ids)diff --git a/tests/agent/test_codex_pending_tool_text.py b/tests/agent/test_codex_pending_tool_text.pyindex 39a10c7c2af..485ce670183 100644--- a/tests/agent/test_codex_pending_tool_text.py+++ b/tests/agent/test_codex_pending_tool_text.py@@ -8,6 +8,8 @@ skipped too, so the narration vanished from the turn: no bubble, an empty storedfrom types import SimpleNamespace as NS+import pytest+from agent.codex_responses_adapter import _normalize_codex_responsefrom agent.codex_runtime import _consume_codex_event_stream@@ -51,3 +53,23 @@ def test_narration_beside_a_call_is_carried_once():assistant, _finish = _normalize_codex_response(response)assert (assistant.content or "").count(NARRATION) == 1assert [c.function.name for c in assistant.tool_calls] == ["read_file"]+++def test_a_stream_cut_before_its_terminal_frame_still_fails_for_a_retry():+ """Answer announced, partial text, a call announced, then the connection ends with no terminal frame: the+ turn must fail and retry, never complete on the cut-off sentence with the announced call dropped. Later+ commentary named by its item id stays narration, never fused into the recovered answer."""+ cut = _stream(with_commentary=False)[:4] # created, call added, answer added, partial answer delta+ with pytest.raises(RuntimeError, match="did not emit a terminal response"):+ _consume_codex_event_stream(iter(cut), model="m")++ commentary = NS(id="msg_c", type="message", role="assistant", status="in_progress", phase="commentary", content=[])+ events = _stream(with_commentary=False)+ events[4:4] = [NS(type="response.output_item.added", output_index=3, item=commentary),+ NS(type="response.output_item.added", output_index=4,+ item=NS(id="fc_2", type="function_call", call_id="call_2", name="read_file", arguments="",+ status="in_progress")),+ NS(type="response.output_text.delta", item_id="msg_c", output_index=3, delta="more planning")]+ assistant, _finish = _normalize_codex_response(_consume_codex_event_stream(iter(events), model="m"))+ assert "more planning" not in (assistant.content or "")+ assert NARRATION in (assistant.content or "")diff --git a/tests/hermes_state/test_compaction_carried_tail_not_cloned.py b/tests/hermes_state/test_compaction_carried_tail_not_cloned.pyindex ca5fa1bab9b..43c34948930 100644--- a/tests/hermes_state/test_compaction_carried_tail_not_cloned.py+++ b/tests/hermes_state/test_compaction_carried_tail_not_cloned.py@@ -15,6 +15,7 @@ from pathlib import Pathimport pytest+from agent.message_metadata import RESTORED_FROM_STOREfrom hermes_state import SessionDBSID = "sess1"@@ -95,3 +96,29 @@ class TestCarriedTailAboveWatermark:assert len(copies) == 4, "held original + its carried copy, foreign original + its clone"assert sorted(r["active"] for r in copies) == [0, 0, 1, 1]assert len({r["message_uid"] for r in copies if r["active"]}) == 2+++def test_a_colliding_stored_row_is_never_dropped(db: SessionDB) -> None:+ """A carried copy or a restored dict may only stand for the stored row it really is: a different message+ that shares its text and timestamp, its uid with newer content, or bare text keeps a live row or stays+ visible; a restored dict edited since its row was read keeps its edit."""+ db.append_messages_batch(SID, [{"role": "user", "content": "ok", "timestamp": 1000.0},+ {"role": "assistant", "content": "draft answer", "timestamp": 1001.0}])+ held_ok, held_draft = db.get_messages_as_conversation(SID, include_row_ids=True)[-2:]+ watermark = db.get_active_message_watermark(SID)+ db.append_messages_batch(SID, [+ {"role": "user", "content": "ok", "timestamp": 1000.0}, # another "ok" at the same second+ {"role": "assistant", "content": "edited answer", "timestamp": 1002.0, "message_uid": held_draft["message_uid"]},+ {"role": "user", "content": "continue", "timestamp": 1003.0}]) # another surface's identical text+ db.archive_and_compact(SID, [_summary(), held_ok, held_draft, {"role": "user", "content": "continue"}],+ watermark=watermark, tail_count=3)++ live = [m["content"] for m in db.get_messages_as_conversation(SID)]+ assert live.count("ok") == 2 and "edited answer" in live+ assert [m["content"] for m in db.get_messages(SID, include_compacted=True)].count("continue") == 2++ restored = db.get_messages_as_conversation(SID)[-1]+ restored.update({"content": "continue, and also this", RESTORED_FROM_STORE: True})+ restored.pop("_db_persisted", None)+ db.append_messages_batch(SID, [restored])+ assert "continue, and also this" in [m["content"] for m in db.get_messages_as_conversation(SID)]