Skip to content

The agent that grows with you

fix(compression): in-place compaction accounts for the rows the repair drops

John Paul Soliva7e3bc5b60da3
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 5db6e7c449b..b51364a0469 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -467,6 +467,8 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,
text survives). An empty incoming turn still merges; stamping an empty list would change a message that
absorbed nothing. A dropped id that equals the survivor's own live id (the display-marker merge adopts
the plain row's id, #94486) is not an absorbed row: the survivor IS that row."""
+ from agent.conversation_compression_archive import DROPPED_DURABLE_ROWS
+
own_id = survivor.get("_row_id")
ids = []
row_id = dropped.get("_row_id")
@@ -480,12 +482,30 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,
for row_id in ids:
if row_id not in absorbed:
absorbed.append(row_id)
+ # Rows the repair dropped behind the retired dict are behind the survivor now.
+ if dropped.get(DROPPED_DURABLE_ROWS):
+ survivor[DROPPED_DURABLE_ROWS] = int(survivor.get(DROPPED_DURABLE_ROWS) or 0) + int(dropped[DROPPED_DURABLE_ROWS])
# The uid witness claims the dropped dict's TEXT lives on in the survivor: only a fold earns it. A
# superseded row (``folded=False``) is retired like any absorbed row but its content is discarded.
if folded:
record_absorbed_message(survivor, dropped)
+def _retire_dropped_row(kept: List[Dict], dropped: Dict[str, Any]) -> None:
+ """A durable row the repair drops was still handed to the caller, so the survivor before it stands
+ for it. Left unnamed, an in-place compaction takes it for a row another surface appended and
+ re-sequences it behind the running turn. A reload without row ids can only count it."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ from agent.conversation_compression_archive import DROPPED_DURABLE_ROWS
+
+ prev = kept[-1] if kept and isinstance(kept[-1], dict) else None
+ if prev is None or not dropped.get(_DB_PERSISTED_MARKER):
+ return
+ _remember_absorbed_row(prev, dropped, folded=False)
+ if not isinstance(dropped.get("_row_id"), int):
+ prev[DROPPED_DURABLE_ROWS] = int(prev.get(DROPPED_DURABLE_ROWS) or 0) + 1
+
+
def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:
"""Pass 0: merge consecutive assistant turns (codex interims exempt)."""
repairs = 0
@@ -543,6 +563,7 @@ 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)
repairs += 1
continue
if candidate_groups:
@@ -578,6 +599,7 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]
repairs += 1
if 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)
continue
if kept_calls:
msg["tool_calls"] = kept_calls
diff --git a/agent/conversation_compression_archive.py b/agent/conversation_compression_archive.py
index 0b17f73c4fb..d849ca9c4cc 100644
--- a/agent/conversation_compression_archive.py
+++ b/agent/conversation_compression_archive.py
@@ -14,6 +14,9 @@ ABSORBED_ROW_IDS = "_absorbed_row_ids"
# How many durable rows an alternation repair folded into one user dict. A reload without row ids
# has no other way to tell that dict from a prompt that was never persisted.
MERGED_DURABLE_ROWS = "_merged_durable_rows"
+# How many durable rows the repair dropped behind a dict on a reload without row ids (a tool call
+# with no result, a result with no call). The caller was handed them, and nothing else names them.
+DROPPED_DURABLE_ROWS = "_dropped_durable_rows"
def _positive_id(value: Any) -> Optional[int]:
@@ -82,9 +85,10 @@ def coverage_for_commit(
"""Coverage to pass into ``archive_and_compact``, or ``(None, None)`` to keep the watermark.
``None`` when the newest exact held row is already inactive (another compaction
- won: archiving only the held ids would clone the winner) or when nothing held
- is a durable row. A trailing unpersisted turn does not take this branch: the
- rows above it stay unnamed and are cloned.
+ won: archiving only the held ids would clone the winner), when nothing held
+ is a durable row, or when a row the repair dropped has no id: naming the rest
+ would clone that one behind the running turn. A trailing unpersisted turn
+ does not take this branch: the rows above it stay unnamed and are cloned.
"""
from agent.context_compressor import _DB_PERSISTED_MARKER
@@ -93,6 +97,8 @@ def coverage_for_commit(
if newest is not None and callable(role_of) and role_of(session_id, newest) is None:
return None, None
covered, unresolved = held_archive_coverage(messages, verbatim_tail)
+ if any(message.get(DROPPED_DURABLE_ROWS) for message in unresolved):
+ return None, None
marked = [
message for message in unresolved
if isinstance(message, dict) and message.get(_DB_PERSISTED_MARKER)
diff --git a/gateway/run.py b/gateway/run.py
index 56d1c2299ef..0c0b190bb62 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1157,8 +1157,10 @@ def _build_replay_entry(
if msg.get("_db_persisted"):
entry["_db_persisted"] = True
# A merged user dict lost that stamp; this one is what ties it to its durable rows at compaction.
- if msg.get("_merged_durable_rows"):
- entry["_merged_durable_rows"] = msg["_merged_durable_rows"]
+ # The other counts the rows the repair dropped behind a dict, which this view cannot name either.
+ for stamp in ("_merged_durable_rows", "_dropped_durable_rows"):
+ if msg.get(stamp):
+ entry[stamp] = msg[stamp]
return entry
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 56545c93a32..d0f32a185a5 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1081,17 +1081,22 @@ class SessionMessagesMixin:
def _uncounted_merged_rows(tail: List[Dict[str, Any]]) -> int:
"""Durable rows behind the carried *tail* beyond one per dict, for the positional rewind.
- The watermark path cannot name a merged dict's run, so it widens by the stamp. A dict that
- lists ``_absorbed_row_ids`` is already counted in ``tail_count``, and one that holds a
- ``_row_id`` was written back as a single row by an earlier compaction.
+ The watermark path cannot name a merged dict's run, so it widens by the stamp, less the
+ rows the dict lists in ``_absorbed_row_ids``: those are already counted in ``tail_count``.
+ Rows the repair dropped behind a dict on a reload without ids are in neither, so their
+ count is added. A dict that holds a ``_row_id`` was written back as a single row by an
+ earlier compaction.
"""
- from agent.conversation_compression_archive import MERGED_DURABLE_ROWS
+ from agent.conversation_compression_archive import DROPPED_DURABLE_ROWS, MERGED_DURABLE_ROWS
+
+ def behind(message: Dict[str, Any]) -> int:
+ merged, dropped = message.get(MERGED_DURABLE_ROWS), message.get(DROPPED_DURABLE_ROWS)
+ unnamed = merged - 1 - len(message.get("_absorbed_row_ids") or ()) if type(merged) is int else 0
+ return max(0, unnamed) + (dropped if type(dropped) is int else 0)
return sum(
- message[MERGED_DURABLE_ROWS] - 1 for message in tail
- if isinstance(message, dict) and type(message.get(MERGED_DURABLE_ROWS)) is int
- and message[MERGED_DURABLE_ROWS] > 1 and not message.get("_absorbed_row_ids")
- and not isinstance(message.get("_row_id"), int))
+ behind(message) for message in tail
+ if isinstance(message, dict) and not isinstance(message.get("_row_id"), int))
@staticmethod
def _tail_originals(covered_active: List[int], tail_count: int, merged_away: Set[int]) -> List[int]:
diff --git a/tests/agent/test_in_place_merged_user_rows.py b/tests/agent/test_in_place_merged_user_rows.py
index 1a5cb602612..fc1302f48e2 100644
--- a/tests/agent/test_in_place_merged_user_rows.py
+++ b/tests/agent/test_in_place_merged_user_rows.py
@@ -1,7 +1,9 @@
-"""In-place compaction over a prompt that never got its reply.
+"""In-place compaction over a turn that was killed before it finished.
A crash between turn start and the reply leaves a durable ``user;user`` pair. The alternation repair
hands the compressor one dict for both rows, so the commit has to account for two originals behind it.
+A turn killed later leaves a tool call with no result, or a result the repair cannot pair. The repair
+drops those rows, and they are still behind the dict before them.
"""
from types import SimpleNamespace
@@ -10,18 +12,34 @@ import pytest
from tests.agent.test_in_place_preflight_rewind import _replies_displayed, _turn, session # noqa: F401
-UNANSWERED = "U12x this prompt never got a reply"
-
-
[email protected]("surface", ["cli", "gateway"])
-def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(session, surface):
+_UNANSWERED = ("user", "U12x this prompt never got a reply", {})
+_RETRIED = ("user", "U12y the same request again", {})
+_CALL = ("assistant", "", {"tool_calls": [
+ {"id": "call_killed", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}]})
+_RESULT = ("tool", "partial output", {"tool_call_id": "call_killed"})
+KILLED_TURN_LEFT = {
+ "prompt": [_UNANSWERED],
+ "two_prompts": [_UNANSWERED, _RETRIED],
+ "tool_call": [_UNANSWERED, _CALL],
+ "tool_result": [_UNANSWERED, _RESULT],
+ "two_prompts_tool_call": [_UNANSWERED, _RETRIED, _CALL],
+ "result_after_a_reply": [_RESULT],
+}
+
+
[email protected]("surface", ["cli", "resume", "gateway"])
[email protected]("left", list(KILLED_TURN_LEFT))
+def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(session, surface, left):
db, agent = session
cli = SimpleNamespace(conversation_history=[])
for n in range(1, 13):
_turn(db, agent, cli, surface, n, 5_000)
- db.append_message("sid", "user", UNANSWERED)
- if surface == "cli": # a resumed CLI session starts from the repaired reload
+ for role, content, fields in KILLED_TURN_LEFT[left]:
+ db.append_message("sid", role, content, **fields)
+ if surface == "cli": # ACP and the classic CLI restore start from the repaired reload
cli.conversation_history = db.get_messages_as_conversation("sid", repair_alternation=True)
+ elif surface == "resume": # --resume and the TUI load the same history with row ids
+ cli.conversation_history = db.get_resume_conversations("sid")[0]
_turn(db, agent, cli, surface, 13, 5_000)
_turn(db, agent, cli, surface, 14, 200_000) # real usage over the threshold: the next turn compacts first
@@ -30,8 +48,15 @@ def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(sessio
assert getattr(agent, "_last_compaction_in_place", None) is True
assert {f"A{n}" for n in range(1, 16)} <= _replies_displayed(db)
live = [m["content"] for m in db.get_messages_as_conversation("sid") if isinstance(m.get("content"), str)]
- assert [c for c in live if UNANSWERED in c] == [f"{UNANSWERED}\n\nU13 please continue with the next step"]
+ # The prompts the killed turn left are in exactly one live row, the merged carried copy.
+ unanswered = [c for role, c, _ in KILLED_TURN_LEFT[left] if role == "user"]
+ merged = "\n\n".join([*unanswered, "U13 please continue with the next step"])
+ assert [c for c in live if "U12x" in c or "U12y" in c] == ([merged] if unanswered else [])
recalled = [row["content"] for row in db._conn.execute(
"SELECT content FROM messages WHERE session_id = 'sid' AND (active = 1 OR compacted = 1)").fetchall()]
carried = live[next(i for i, c in enumerate(live) if "Numbered steps" in c) + 1:]
assert [recalled.count(content) for content in carried] == [1] * len(carried)
+ # No turn here uses a tool, so a live tool row is the killed turn's, appended behind the running turn.
+ assert db._conn.execute(
+ "SELECT COUNT(*) FROM messages WHERE session_id = 'sid' AND active = 1"
+ " AND (role = 'tool' OR tool_calls IS NOT NULL)").fetchone()[0] == 0