Skip to content

The agent that grows with you

fix(state): adopt an untracked compression chain longer than one walk

unsupportedpastels2516b6e733b1
diff --git a/hermes_state_local_lineage.py b/hermes_state_local_lineage.py
index 5d0bcc9be9e..395d3d3c26e 100644
--- a/hermes_state_local_lineage.py
+++ b/hermes_state_local_lineage.py
@@ -99,6 +99,26 @@ def advance_local_target(conn, parent_session_id, child_session_id, *, entry=Non
_commit_local_target(conn, receipt, candidate)
+def _untracked_steps(conn, tip, lineage):
+ """Every compression step past *tip*, in order; None when the chain leads back into itself.
+
+ One ``_walk_compression_chain`` stops after ``_CHAIN_CAP`` steps, which is not the end of the
+ chain: walk on from the last step until a walk finds nothing more. Each batch only adds ids never
+ seen, so the walk ends; a step back into the lineage or an earlier batch is a cycle.
+ """
+ from hermes_state_compression import _CHAIN_STEP_SQL, _walk_compression_chain
+ steps, seen, current = [], {*lineage, tip}, tip
+ while True:
+ batch = _walk_compression_chain(current, lambda sid: conn.execute(_CHAIN_STEP_SQL, (sid,)).fetchone())[1:]
+ if not batch:
+ return steps
+ if seen.intersection(batch):
+ return None
+ seen.update(batch)
+ steps.extend(batch)
+ current = batch[-1]
+
+
def untracked_compression_tip(conn, receipt):
"""The compression child of *receipt*'s tip, when the receipt does not record it yet."""
from hermes_state_compression import _CHAIN_STEP_SQL
@@ -118,8 +138,6 @@ def adopt_untracked_compression(db, *, epoch, session_id, expected):
it, nothing else. The stored receipt must still be *expected*, the copy the caller checked
against its owner. Anything else is left for validation to refuse, unchanged.
"""
- from hermes_state_compression import _CHAIN_STEP_SQL, _walk_compression_chain
-
def write(conn):
_epoch(conn, epoch)
saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + session_id,)).fetchone()
@@ -129,10 +147,10 @@ def adopt_untracked_compression(db, *, epoch, session_id, expected):
identity = (receipt['route'], receipt['session_id'], receipt['principal_id'])
lineage = list(receipt.get('lineage', [session_id]))
tip = receipt['entry']['session_id']
- children = _walk_compression_chain(tip, lambda current: conn.execute(_CHAIN_STEP_SQL, (current,)).fetchone())[1:]
- for child_id in children:
+ children = _untracked_steps(conn, tip, lineage)
+ for child_id in children or ():
child = conn.execute('SELECT session_key,chat_id,user_id FROM sessions WHERE id=?', (child_id,)).fetchone()
- if child_id in lineage or tuple(child) != identity:
+ if tuple(child) != identity:
return
routed = _routed_entry(conn, receipt['route'], tip)
if not children or routed is None:
diff --git a/tests/gateway/test_local_receipt_untracked_compression.py b/tests/gateway/test_local_receipt_untracked_compression.py
index 5428c149aa2..a0e79e0d0c2 100644
--- a/tests/gateway/test_local_receipt_untracked_compression.py
+++ b/tests/gateway/test_local_receipt_untracked_compression.py
@@ -45,6 +45,19 @@ def _compact_like_0_22_2(db, parent_id, child_id, *, route_columns=True):
db.append_message(child_id, 'user', f'after compression into {child_id}')
+def _compact_chain_like_0_22_2(db, parent_id, child_ids):
+ """``_compact_like_0_22_2`` over a whole chain of children, in one transaction."""
+ def write(conn):
+ parent = conn.execute('SELECT * FROM sessions WHERE id=?', (parent_id,)).fetchone()
+ route = (parent['user_id'], parent['session_key'], parent['chat_id'], parent['chat_type'], parent['origin_json'])
+ for step_id, child_id in zip([parent_id, *child_ids], child_ids):
+ conn.execute("UPDATE sessions SET ended_at=?, end_reason='compression' WHERE id=?", (time.time(), step_id))
+ conn.execute('''INSERT INTO sessions(id,source,model,parent_session_id,cwd,profile_name,
+ user_id,session_key,chat_id,chat_type,origin_json,started_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)''',
+ (child_id, 'tui', parent['model'], step_id, parent['cwd'], parent['profile_name'], *route, time.time()))
+ db._execute_write(write)
+
+
def _receipt(db, sid):
from hermes_state_local import local_receipt
return local_receipt(db, sid)
@@ -200,6 +213,71 @@ async def test_a_compacted_secondary_receipt_missing_its_origin_profile_restores
process_ownership.release(home)
+async def test_a_compression_chain_longer_than_one_walk_is_adopted_whole(tmp_path, monkeypatch):
+ """The catch-up walks the untracked steps in ``_CHAIN_CAP`` batches: a chain one step longer than a
+ single walk is still complete and valid, so it is adopted to its real tip instead of being refused
+ (and rolled back) on every restore."""
+ from gateway.session_local import create_local_session
+ from hermes_state_compression import _CHAIN_CAP
+
+ first, connection = await _owner(tmp_path, monkeypatch, 'first')
+ ref = create_local_session(first, connection.actor, {'request_id': 'r', 'source': 'tui',
+ 'cwd': str(tmp_path), 'model': 'm', 'toolsets': []})
+ db_path = first.db.db_path
+ await connection.close()
+ first.db.close()
+
+ from hermes_state import SessionDB
+ classic = SessionDB(db_path=db_path)
+ children = [f'classic-child-{n}' for n in range(_CHAIN_CAP + 1)]
+ _compact_chain_like_0_22_2(classic, ref.session_id, children)
+ classic.close()
+
+ second, connection = await _owner(tmp_path, monkeypatch, 'second')
+ try:
+ assert ref.session_id in second.sessions, 'the long chain was paused on cold recovery'
+ receipt = _receipt(second.db, ref.session_id)
+ assert receipt['lineage'] == [ref.session_id, *children]
+ assert receipt['entry']['session_id'] == children[-1]
+ finally:
+ await connection.close()
+ second.db.close()
+
+
+async def test_a_chain_that_loops_back_past_one_walk_is_not_adopted(tmp_path, monkeypatch):
+ """Cycle detection holds across batches: a chain longer than one walk whose last step leads back
+ into the receipt's lineage is never adopted, and the receipt stays as stored."""
+ from gateway.session_local import create_local_session
+ from hermes_state_compression import _CHAIN_CAP
+
+ first, connection = await _owner(tmp_path, monkeypatch, 'first')
+ ref = create_local_session(first, connection.actor, {'request_id': 'r', 'source': 'tui',
+ 'cwd': str(tmp_path), 'model': 'm', 'toolsets': []})
+ before = json.loads(json.dumps(_receipt(first.db, ref.session_id)))
+ db_path = first.db.db_path
+ await connection.close()
+ first.db.close()
+
+ from hermes_state import SessionDB
+ classic = SessionDB(db_path=db_path)
+ children = [f'classic-child-{n}' for n in range(_CHAIN_CAP + 1)]
+ _compact_chain_like_0_22_2(classic, ref.session_id, children)
+ classic._execute_write(lambda conn: (
+ conn.execute("UPDATE sessions SET end_reason='compression' WHERE id=?", (children[-1],)),
+ conn.execute('UPDATE sessions SET parent_session_id=? WHERE id=?', (children[-1], ref.session_id))))
+ classic.close()
+
+ second, connection = await _owner(tmp_path, monkeypatch, 'second')
+ try:
+ assert ref.session_id not in second.sessions
+ assert _receipt(second.db, ref.session_id) == before
+ finally:
+ await connection.close()
+ second.db.close()
+
+
@pytest.mark.asyncio
async def test_a_restore_with_nothing_to_adopt_checks_the_stored_entry_once(tmp_path, monkeypatch):
"""The catch-up re-checks the receipt only when it moved it. Every LOCAL turn claim restores, so a