Skip to content

The agent that grows with you

fix(gateway): a resume's live rows keep stored order after a rotated compression

Tekniumcf983f7812f0
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index 28fd17837ed..8b5cec6ba6a 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -245,6 +245,32 @@ async def prepare_history(authority, ref):
return target, await asyncio.to_thread(display_rows, authority.db, target)
+def _merge_live_in_stored_order(display, live):
+ """The live rows in stored (``row_id``) order, each archived display row placed before the live
+ row it preceded in display order.
+
+ Display deduplication keeps a carried message at its FIRST copy's position, so after a rotated
+ compression the copied tail sits before the new summary. Clients take the live rows of a resume
+ as the transcript (the CLI's ``conversation_history``, ``/undo``'s prefix, rollback, ACP replay),
+ so the live subsequence must be the stored one; archived rows only anchor between live rows."""
+ current = {row['_row_id'] for row in live}
+ groups, pending, shown = [], [], 0
+ for row in display:
+ if row['_row_id'] in current:
+ groups.append(pending)
+ pending, shown = [], shown + 1
+ else:
+ pending.append({**row, 'archived': True})
+ shown_ids = {row['_row_id'] for row in display} & current
+ rows, seen = [], 0
+ for row in sorted(live, key=lambda r: r['_row_id']):
+ if row['_row_id'] in shown_ids:
+ rows.extend(groups[seen])
+ seen += 1
+ rows.append(row)
+ return rows + pending
+
+
def local_history(authority, ref, prepared=None):
"""Display history of logical *ref*: every stored row the user saw, in display order.
@@ -269,18 +295,8 @@ def local_history(authority, ref, prepared=None):
if not read_live <= {row['_row_id'] for row in live}:
read_live, display, truncated = display_rows(db, target)
live = db.get_messages_as_conversation(target, include_row_ids=True)
- current = {row['_row_id']: row for row in live}
- shown = {row['_row_id'] for row in display}
- unshown = [row for row in live if row['_row_id'] not in shown] # hidden by the display, or appended since
- rows = []
- for row in display:
- if row['_row_id'] not in current:
- rows.append({**row, 'archived': True})
- continue
- while unshown and unshown[0]['_row_id'] < row['_row_id']:
- rows.append(unshown.pop(0))
- rows.append(current[row['_row_id']])
- rows = [{**{k: v for k, v in row.items() if k != '_row_id'}, 'row_id': row['_row_id']} for row in rows + unshown]
+ rows = [{**{k: v for k, v in row.items() if k != '_row_id'}, 'row_id': row['_row_id']}
+ for row in _merge_live_in_stored_order(display, live)]
if truncated and rows:
rows[0]['archived_truncated'] = True # earlier archived history was left out (the byte budget)
return rows
diff --git a/tests/gateway/test_resume_display_history.py b/tests/gateway/test_resume_display_history.py
index 6c3b5fcd80a..9f022472a29 100644
--- a/tests/gateway/test_resume_display_history.py
+++ b/tests/gateway/test_resume_display_history.py
@@ -73,10 +73,28 @@ async def test_resume_shows_the_turns_a_compression_archived(tmp_path, monkeypat
tip = _compact(db, physical, mode)
rows = (await _resume(authority, actor, ref))['messages']
# The earlier turns are shown and marked archived; the carried tail appears once; a rewound turn stays out.
- assert [(r['content'], bool(r.get('archived'))) for r in rows if r['content'] != SUMMARY] == [
- ('OLD_Q', True), ('OLD_A', True), ('TAIL_Q', False), ('TAIL_A', False)]
+ # The summary sits before the tail it precedes in the store, in both modes.
+ assert [(r['content'], bool(r.get('archived'))) for r in rows] == [
+ ('OLD_Q', True), ('OLD_A', True), (SUMMARY, False), ('TAIL_Q', False), ('TAIL_A', False)]
# The rows not archived are exactly the live transcript, each with its durable row id.
- assert sorted(r['row_id'] for r in rows if not r.get('archived')) == [m['id'] for m in db.get_messages(tip)]
+ assert [r['row_id'] for r in rows if not r.get('archived')] == [m['id'] for m in db.get_messages(tip)]
+
+
+async def test_cli_undo_prefix_keeps_the_summary_after_a_rotated_compression(tmp_path, monkeypatch):
+ """``GatewaySessionStore.rewind_user_turn`` and ``/compress`` take the live rows as the CLI's history:
+ the prefix before the newest user turn holds the summary the store keeps active (review of #140971)."""
+ from agent.context_compressor import history_before_user_originated_turn
+ from hermes_state_rewind import _user_indices
+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)
+ db = authority.db
+ _append(db, physical, 'OLD_Q', 'OLD_A', 'TAIL_Q', 'TAIL_A')
+ _compact(db, physical, 'rotated')
+ _append(db, 'child', 'NEW_Q', 'NEW_A')
+ live = [r for r in (await _resume(authority, actor, ref))['messages'] if not r.get('archived')]
+ prefix, turn = history_before_user_originated_turn(live, _user_indices(live)[-1])
+ assert turn['content'] == 'NEW_Q'
+ assert [m['content'] for m in prefix] == [SUMMARY, 'TAIL_Q', 'TAIL_A']
@pytest.mark.asyncio
@@ -147,6 +165,6 @@ async def test_a_long_archived_history_keeps_the_resume_reply_bounded(tmp_path,
assert len(json.dumps(reply)) < 8 * 1024 * 1024
rows = reply['messages']
assert rows[0]['archived_truncated'] and rows[-1]['content'] == 'R23'
- assert sorted(r['row_id'] for r in rows if not r.get('archived')) == [m['id'] for m in db.get_messages(tip)]
+ assert [r['row_id'] for r in rows if not r.get('archived')] == [m['id'] for m in db.get_messages(tip)]
archived = [r['content'][:4] for r in rows if r.get('archived') and r['role'] == 'user']
assert archived and archived[-1] == 'Q39 ' and 'Q0 x' not in archived # the newest are kept