Skip to content

The agent that grows with you

feat: preserve worker history and cache lineage identities

Tekniume63e1101c02a
diff --git a/agent/runtime_session_compression.py b/agent/runtime_session_compression.py
index cbb8aa790de..ef2376b181a 100644
--- a/agent/runtime_session_compression.py
+++ b/agent/runtime_session_compression.py
@@ -2,6 +2,41 @@
class RuntimeSessionCompressionMixin:
+ def get_session(self, session_id):
+ if session_id != self.scope['session_id']:
+ from agent.runtime_session_store import WorkerPersistenceError
+ ids = self._apply('compression.lineage', {'target': self.scope['session_id']})['readable_ids']
+ if session_id not in ids:
+ raise WorkerPersistenceError('permission_denied')
+ return self._apply('compression.context', {'target': session_id})['session']
+
+ def get_compression_lineage(self, session_id):
+ return self._apply('compression.lineage', {'target': session_id})['lineage']
+
+ def get_conversation_root(self, session_id):
+ return self._apply('compression.lineage', {'target': session_id})['root']
+
+ def get_compression_tip(self, session_id):
+ return self._apply('compression.lineage', {'target': session_id})['tip']
+
+ def resolve_resume_session_id(self, session_id):
+ return self._apply('compression.lineage', {'target': session_id})['resume']
+
+ def declared_scope_identity(self, session_id):
+ return tuple(self._apply('compression.lineage', {'target': session_id})['identity'])
+
+ def is_explicit_fork_child(self, session_id):
+ return self.declared_scope_identity(session_id)[0]
+
+ def latest_conversation_boundary(self, session_key, source):
+ return self._apply('compression.boundary', {'session_key': session_key, 'source': source})['value']
+
+ def get_messages_as_conversation(self, session_id, include_ancestors=False, include_inactive=False,
+ repair_alternation=False, include_row_ids=False, include_compacted=False):
+ return self._apply('compression.history', dict(target=session_id, include_ancestors=include_ancestors,
+ include_inactive=include_inactive, repair_alternation=repair_alternation,
+ include_row_ids=include_row_ids, include_compacted=include_compacted))['messages']
+
def try_acquire_compression_lock(self, session_id, holder, ttl_seconds=300.0):
self._session(session_id)
return self._apply('compression.lock.acquire', {'holder': holder, 'ttl_seconds': ttl_seconds})['value']
diff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.py
index 8f18424ba78..ee20140358f 100644
--- a/hermes_state_worker_compression.py
+++ b/hermes_state_worker_compression.py
@@ -98,7 +98,109 @@ def worker_compression_counter(db, conn, sid, payload, *, column):
return {'value': None}
+class CompressionSnapshot:
+ """Reuse production read algorithms on the receipt connection, never a second handle.
+
+ Only read primitives are provided; this object cannot start/commit a write.
+ Wire handlers below select concrete projections, not caller-named methods.
+ """
+ from hermes_state_compression import SessionCompressionMixin as _C
+ from hermes_state_messages import SessionMessagesMixin as _M
+ from hermes_state_sessions import SessionSessionsMixin as _S
+
+ get_compression_chain = _C.get_compression_chain
+ get_compression_tip = _C.get_compression_tip
+ get_compression_lineage = _C.get_compression_lineage
+ _is_compression_child_row = _C._is_compression_child_row
+ _session_lineage_root_to_tip = _S._session_lineage_root_to_tip
+ _is_explicit_branch_session = _S._is_explicit_branch_session
+ declared_scope_identity = _S.declared_scope_identity
+ _resume_lineage_ids = _M._resume_lineage_ids
+ get_conversation_root = _M.get_conversation_root
+ resolve_resume_session_id = _M.resolve_resume_session_id
+ latest_conversation_boundary = _M.latest_conversation_boundary
+ _is_explicit_fork_child_row = _M._is_explicit_fork_child_row
+
+ def __init__(self, db, conn):
+ self.db, self.conn = db, conn
+
+ def _read_ctx(self):
+ from contextlib import nullcontext
+ return nullcontext(self.conn)
+
+ def _read_one(self, sql, params=()):
+ return self.conn.execute(sql, params).fetchone()
+
+ def _read_all(self, sql, params=()):
+ return self.conn.execute(sql, params).fetchall()
+
+ def get_session(self, sid):
+ from hermes_state_worker_context import worker_context
+ return worker_context(self.db, self.conn, sid, {})['session']
+
+ def authorize(self, assigned, target):
+ _text(target)
+ # Attribution ancestry is readable; unrelated siblings and foreign trees are not.
+ allowed = self._session_lineage_root_to_tip(assigned)
+ allowed += self.get_compression_chain(assigned)
+ if target not in allowed:
+ raise RuntimeStoreError('permission_denied')
+
+
+def worker_lineage_context(db, conn, sid, payload):
+ _fields(payload, ('target',))
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ return {'session': view.get_session(target)}
+
+
+def worker_lineage(db, conn, sid, payload):
+ _fields(payload, ('target',))
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ return {'readable_ids': view._session_lineage_root_to_tip(sid) + view.get_compression_chain(sid),
+ 'lineage': view.get_compression_lineage(target),
+ 'root': view.get_conversation_root(target),
+ 'tip': view.get_compression_tip(target),
+ 'resume': view.resolve_resume_session_id(target),
+ 'identity': view.declared_scope_identity(target)}
+
+
+def worker_boundary(db, conn, sid, payload):
+ _fields(payload, ('session_key', 'source'))
+ view = CompressionSnapshot(db, conn)
+ row = view.get_session(sid)
+ if (row['session_key'], row['source']) != (payload['session_key'], payload['source']):
+ raise RuntimeStoreError('permission_denied')
+ return {'value': view.latest_conversation_boundary(payload['session_key'], payload['source'])}
+
+
+def worker_history(db, conn, sid, payload):
+ _fields(payload, ('target', 'include_ancestors', 'include_inactive', 'repair_alternation',
+ 'include_row_ids', 'include_compacted'))
+ if any(type(v) is not bool for k, v in payload.items() if k != 'target'):
+ raise RuntimeStoreError('invalid_params')
+ view = CompressionSnapshot(db, conn)
+ target = payload['target']
+ view.authorize(sid, target)
+ ids = view._resume_lineage_ids(target) if payload['include_ancestors'] else [target]
+ active = db._active_clause(payload['include_inactive'], payload['include_compacted'])
+ rows = conn.execute(f'SELECT {db._CONVERSATION_ROW_COLUMNS} FROM messages '
+ f'WHERE session_id IN ({",".join("?" for _ in ids)}){active} ORDER BY id', ids).fetchall()
+ if payload['include_compacted']:
+ rows = db._dedupe_display_generations(rows)
+ return {'messages': db._rows_to_conversation(rows, session_id=target,
+ include_ancestors=payload['include_ancestors'], repair_alternation=payload['repair_alternation'],
+ include_row_ids=payload['include_row_ids'])}
+
+
WORKER_COMPRESSION_HANDLERS = {
+ 'compression.context': worker_lineage_context,
+ 'compression.lineage': worker_lineage,
+ 'compression.boundary': worker_boundary,
+ 'compression.history': worker_history,
**{'compression.lock.' + action: partial(worker_compression_lock, action=action)
for action in ('acquire', 'renew', 'release', 'holder')},
'compression.cooldown.record': worker_cooldown_record,
diff --git a/tests/state/test_runtime_worker_history.py b/tests/state/test_runtime_worker_history.py
new file mode 100644
index 00000000000..0bae5208191
--- /dev/null
+++ b/tests/state/test_runtime_worker_history.py
@@ -0,0 +1,70 @@
+"""Read receipts preserve replay markers and distinct cache/attribution roots."""
+from types import SimpleNamespace
+
+import pytest
+
+from agent.prompt_cache_scope import resolve_prompt_cache_scope
+from agent.runtime_session_store import RuntimeSessionStore
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch, mutate_worker_execution, register_worker_execution
+
+
+def test_history_and_lineage_keep_cache_scope_distinct_from_attribution(tmp_path):
+ db = SessionDB(tmp_path / 'state.db')
+ try:
+ db.create_session('root', 'cli', system_prompt='root prefix')
+ db.create_session('child', 'cli', parent_session_id='root',
+ model_config={'_delegate_from': 'root'}, system_prompt='child prefix')
+ db.end_session('child', 'compression')
+ db.create_session('tip', 'cli', parent_session_id='child', model_config={'_delegate_from': 'root'},
+ system_prompt='child prefix')
+ db.create_session('foreign', 'cli', system_prompt='secret')
+ db.append_messages_batch('tip', [
+ {'role': 'user', 'content': 'canonical', 'api_content': ' EXACT\nWIRE ', 'platform_message_id': 'delivery'},
+ {'role': 'assistant', 'content': 'answer', 'reasoning': 'reason', 'codex_message_items': [{'type': 'message'}]}])
+ epoch = begin_runtime_epoch(db, instance_id='fixture')
+ scope = dict(epoch=epoch, execution_id='worker', session_id='tip', generation=0)
+ register_worker_execution(db, **scope, kind='compute', adoption_secret='secret')
+ store = RuntimeSessionStore(lambda method, **p: mutate_worker_execution(db, **p), scope, tmp_path / 'outbox')
+ try:
+ assert store.get_messages_as_conversation('tip', include_row_ids=True) == db.get_messages_as_conversation('tip', include_row_ids=True)
+ assert store.get_compression_lineage('tip') == db.get_compression_lineage('tip') == ['child', 'tip']
+ assert store.get_conversation_root('tip') == 'root'
+ assert store.get_session('root')['system_prompt'] == 'root prefix'
+ assert store.get_compression_tip('child') == db.get_compression_tip('child')
+ assert store.resolve_resume_session_id('child') == db.resolve_resume_session_id('child')
+ assert resolve_prompt_cache_scope(SimpleNamespace(session_id='tip', _session_db=store)) == 'child'
+ assert store.declared_scope_identity('child') == (True, 'cli')
+ seq = store.journal['next_sequence']
+ with pytest.raises(Exception, match='permission_denied'):
+ mutate_worker_execution(db, **scope, sequence=seq, operation='compression.context', payload={'target': 'foreign'})
+ assert db._read_one('SELECT last_sequence FROM worker_executions')[0] == seq - 1
+ finally:
+ store.close()
+ finally:
+ db.close()
+
+
+def test_declared_cache_boundary_matches_local_database(tmp_path):
+ db = SessionDB(tmp_path / 'state.db')
+ try:
+ db.create_session('owned', 'cli', session_key='chat')
+ db.end_session('owned', 'session_reset')
+ db.create_session('next', 'cli', session_key='chat')
+ epoch = begin_runtime_epoch(db, instance_id='fixture')
+ scope = dict(epoch=epoch, execution_id='worker', session_id='next', generation=0)
+ register_worker_execution(db, **scope, kind='compute', adoption_secret='secret')
+ store = RuntimeSessionStore(lambda method, **p: mutate_worker_execution(db, **p), scope, tmp_path / 'outbox')
+ try:
+ assert store.latest_conversation_boundary('chat', 'cli') == db.latest_conversation_boundary('chat', 'cli')
+ def agent(handle):
+ return SimpleNamespace(session_id='next', _session_db=handle, _gateway_session_key='chat')
+ assert resolve_prompt_cache_scope(agent(store)) == resolve_prompt_cache_scope(agent(db))
+ with pytest.raises(Exception, match='permission_denied'):
+ store.latest_conversation_boundary('foreign-chat', 'cli')
+ finally:
+ store.failure = None
+ store.journal['pending'] = []
+ store.close()
+ finally:
+ db.close()