The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): a row the repair drops ahead of the first survivor is accounted for
John Paul Soliva6eb90cac31d0
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 78cfd614e5f..f5575b001f6 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -505,14 +505,22 @@ def _count_unnamed_row(survivor: Dict[str, Any], retired: Dict[str, Any]) -> Nonsurvivor[UNNAMED_DURABLE_ROWS] = int(survivor.get(UNNAMED_DURABLE_ROWS) or 0) + 1-def _retire_dropped_row(kept: List[Dict], dropped: Dict[str, Any]) -> None:+def _retire_dropped_row(kept: List[Dict], dropped: Dict[str, Any], leading: List[Dict]) -> None:"""A durable row the repair drops was still handed to the caller, so the survivor before it standsfor it. Left unnamed, an in-place compaction takes it for a row another surface appended and- re-sequences it behind the running turn."""- prev = kept[-1] if kept and isinstance(kept[-1], dict) else None- if prev is not None:- _count_unnamed_row(prev, dropped)- _remember_absorbed_row(prev, dropped, folded=False)+ re-sequences it behind the running turn. A drop with no survivor before it waits in *leading*."""+ if not kept:+ leading.append(dropped)+ elif isinstance(kept[-1], dict):+ _count_unnamed_row(kept[-1], dropped)+ _remember_absorbed_row(kept[-1], dropped, folded=False)+++def _retire_leading_drops(kept: List[Dict], leading: List[Dict]) -> None:+ """Rows dropped ahead of the first survivor sit right before its own row, so it stands for them."""+ for dropped in leading if kept and isinstance(kept[0], dict) else ():+ _count_unnamed_row(kept[0], dropped)+ _remember_absorbed_row(kept[0], dropped, folded=False)def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:@@ -554,6 +562,7 @@ def _drop_stray_tool_results(messages: List[Dict]) -> Tuple[List[Dict], int]:matched_tool_groups: set = set()next_tool_group = 0filtered: List[Dict] = []+ leading: List[Dict] = []for msg in messages:role = msg.get("role") if isinstance(msg, dict) else Noneif role in ("assistant", "user"):@@ -574,12 +583,13 @@ def _drop_stray_tool_results(messages: List[Dict]) -> Tuple[List[Dict], int]:if tc_id in known_tool_ids and known_tool_ids[tc_id] not in matched_tool_groups}if result_variants and not candidate_groups:- _retire_dropped_row(filtered, msg)+ _retire_dropped_row(filtered, msg, leading)repairs += 1continueif candidate_groups:matched_tool_groups.add(min(candidate_groups))filtered.append(msg)+ _retire_leading_drops(filtered, leading)return filtered, repairs@@ -591,6 +601,7 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]repairs = 0pruned: List[Dict] = []+ leading: List[Dict] = []for i, msg in enumerate(messages):if not (isinstance(msg, dict) and msg.get("role") == "assistant" and msg.get("tool_calls")@@ -610,7 +621,7 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]repairs += 1if not kept_calls and not _msg_has_payload({k: v for k, v in msg.items() if k != "tool_calls"}):# Pruned calls were the only payload; drop the turn (empty assistant messages 400).- _retire_dropped_row(pruned, msg)+ _retire_dropped_row(pruned, msg, leading)continueif kept_calls:msg["tool_calls"] = kept_calls@@ -620,6 +631,7 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]# marker, so pop it or the flush scan skips the dict and the DB keeps the old calls.msg.pop(_DB_PERSISTED_MARKER, None)pruned.append(msg)+ _retire_leading_drops(pruned, leading)return pruned, repairsdiff --git a/tests/agent/test_in_place_merged_user_rows.py b/tests/agent/test_in_place_merged_user_rows.pyindex 2fb171e7161..6c2038375d4 100644--- a/tests/agent/test_in_place_merged_user_rows.py+++ b/tests/agent/test_in_place_merged_user_rows.py@@ -70,6 +70,31 @@ def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(sessioassert [c.split(" ")[0] for c in live[-2:]] == ["U15", "A15"][email protected]("row_ids", [True, False])[email protected]("left", ["tool_result", "tool_call"])+def test_a_row_dropped_ahead_of_the_first_survivor_is_archived_with_it(tmp_path, left, row_ids):+ """Nothing is kept before a row the repair drops at the head of the history, so the first+ survivor stands for it."""+ from agent.conversation_compression_archive import coverage_for_commit+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("sid", source="test")+ for role, content, fields in (KILLED_TURN_LEFT[left][-1], ("user", "U1", {}), ("assistant", "A1", {})):+ db.append_message("sid", role, content, **fields)+ watermark = db.get_active_message_watermark("sid")+ held = db.get_messages_as_conversation("sid", repair_alternation=True, include_row_ids=row_ids)+ assert [m["content"] for m in held] == ["U1", "A1"]+ covered_ids, unresolved = coverage_for_commit(db, "sid", held)++ db.archive_and_compact(+ "sid", [{"role": "user", "content": "summary"}], watermark=watermark,+ covered_ids=covered_ids, unresolved_held=unresolved)++ assert [row["content"] for row in db.get_messages("sid")] == ["summary"]+ db.close()++def test_the_repair_row_counts_stay_off_the_request_copy(session):"""The commit reads the counts off the live dict. A transport is handed the request copy, andone that forwards unknown keys must not find them there."""