The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: migrate worker rotation automation inside owner publication
Teknium6fce9f77c6f5
diff --git a/agent/compression_automation.py b/agent/compression_automation.pynew file mode 100644index 00000000000..13f1a5cb64a--- /dev/null+++ b/agent/compression_automation.py@@ -0,0 +1,18 @@+"""Carry automation at a compression boundary without opening worker storage."""+++def carry_compression_automation(agent, old_session_id):+ from agent.runtime_session_store import RuntimeSessionStore+ if isinstance(agent._session_db, RuntimeSessionStore):+ # The owner moved these exact sidecars atomically with child publication.+ return+ from agent.conversation_compression import _swallow+ with _swallow('Could not migrate goal on compression: %s'):+ from hermes_cli.goals import migrate_goal_to_session+ migrate_goal_to_session(old_session_id, agent.session_id, reason='compression')+ with _swallow('Could not migrate heartbeat on compression: %s'):+ from hermes_cli.heartbeat import migrate_heartbeat_to_session+ migrate_heartbeat_to_session(old_session_id, agent.session_id)+ with _swallow('Could not migrate loop on compression: %s'):+ from hermes_cli.loops import migrate_loop_to_session+ migrate_loop_to_session(old_session_id, agent.session_id, reason='compression')diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 7a82999937e..dadb020e9a1 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -2900,18 +2900,8 @@ def _carry_session_state_to_child(agent: Any, old_session_id: str, old_title: Anis carried unchanged (renumbering per rotation made one session look like many); its provenance is read BEFORE thetransfer clears the ancestor's row, then restored so an inherited auto-title stays upgradeable."""- with _swallow('Could not migrate goal on compression: %s'):- # Carry a persistent /goal onto the continuation session. Compression mints a fresh child id;- # load_goal does a flat per-session lookup with no parent walk, so without this an active goal- # silently dies at the boundary (#33618).- from hermes_cli.goals import migrate_goal_to_session- migrate_goal_to_session(old_session_id, agent.session_id, reason="compression")- with _swallow('Could not migrate heartbeat on compression: %s'):- from hermes_cli.heartbeat import migrate_heartbeat_to_session- migrate_heartbeat_to_session(old_session_id, agent.session_id)- with _swallow('Could not migrate loop on compression: %s'):- from hermes_cli.loops import migrate_loop_to_session- migrate_loop_to_session(old_session_id, agent.session_id, reason="compression")+ from agent.compression_automation import carry_compression_automation+ carry_compression_automation(agent, old_session_id)if not old_title:return_src = Nonediff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.pyindex bc9ce32ca51..851530114f2 100644--- a/hermes_state_worker_compression.py+++ b/hermes_state_worker_compression.py@@ -305,6 +305,26 @@ def worker_archive(db, conn, sid, payload):return {'value': value}+def _migrate_worker_automation(db, conn, parent, child):+ from hermes_cli.goals import GoalState+ from hermes_cli.heartbeat import HeartbeatState+ from hermes_cli.loops import LoopState+ for family, state_type in (('goal', GoalState), ('heartbeat', HeartbeatState), ('loop', LoopState)):+ old_key, new_key = f'{family}:{parent}', f'{family}:{child}'+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (old_key,)).fetchone()+ if row is None:+ continue+ state = state_type.from_json(row[0])+ if state.status == 'cleared':+ continue+ prior = conn.execute('SELECT value FROM state_meta WHERE key=?', (new_key,)).fetchone()+ if prior is not None and (family != 'heartbeat' or state_type.from_json(prior[0]).status != 'cleared'):+ continue+ db.set_meta(new_key, state.to_json(), cursor=conn)+ state.status = 'cleared'+ db.set_meta(old_key, state.to_json(), cursor=conn)++def worker_publish(db, conn, sid, payload):from hermes_state_sessions import _parse_model_config_fields(payload, ('child_session_id', 'source', 'messages', 'model', 'model_config', 'system_prompt',@@ -341,6 +361,7 @@ def worker_publish(db, conn, sid, payload):if worker is None:raise RuntimeStoreError('stale_generation')publish_on_connection(db, conn, parent_session_id=sid, **dict(payload, model_config=cfg))+ _migrate_worker_automation(db, conn, sid, child)conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (worker['generation'], child))conn.execute('UPDATE worker_executions SET session_id=? WHERE execution_id=?', (child, worker['execution_id']))conn.execute("UPDATE session_admissions SET target_session_id=?,lineage_json=json_insert(lineage_json,'$[#]',?) "diff --git a/tests/gateway/fixtures/rotation_persistence_worker.py b/tests/gateway/fixtures/rotation_persistence_worker.pynew file mode 100644index 00000000000..3cdefbdd352--- /dev/null+++ b/tests/gateway/fixtures/rotation_persistence_worker.py@@ -0,0 +1,64 @@+"""Registered worker invokes real AIAgent compression over an ordinary daemon."""+import json+import os+from pathlib import Path+import sys++import psutil++from agent.runtime_session_store import RuntimeSessionStore, WorkerRPC+from tests.gateway.fixtures.agent_persistence_worker import writable_fds+++def main():+ command = json.loads(sys.stdin.readline())+ home = Path(command['home'])+ opens = []+ import traceback+ sys.addaudithook(lambda event, args: opens.append({'path': str(args[0]), 'stack': traceback.format_stack(limit=18)})+ if event == 'sqlite3.connect' and 'state.db' in str(args[0]) else None)+ rpc = WorkerRPC(home)+ scope = dict(profile_id=str(home), session_id=command['session_id'], execution_id='compression-worker',+ generation=0, pid=os.getpid(), birth=psutil.Process().create_time(), secret='private-compression-worker')+ registered = rpc('worker.register', **scope, kind='compute')+ scope['epoch'] = registered['owner_epoch']+ store = RuntimeSessionStore(rpc, scope, home / 'worker-outboxes' / 'compression-worker')+ from run_agent import AIAgent+ agent = AIAgent(model='worker-model', provider='custom', base_url=command['url'], api_key='loopback-only',+ session_db=store, session_id=scope['session_id'], enabled_toolsets=[], skip_context_files=True,+ skip_memory=True, skip_background_review=True, quiet_mode=True)+ agent.compression_in_place = False+ frozen_tools = json.loads(json.dumps(agent.tools))+ try:+ # Real compression implementation; only inference is supplied by the loopback peer.+ messages = [{'role': 'system', 'content': 'BYTE_STABLE_PREFIX'}]+ for i in range(12):+ messages.extend([{'role': 'user', 'content': f'USER_{i} ' + 'remember this fact ' * 180},+ {'role': 'assistant', 'content': f'ANSWER_{i} ' + 'acknowledged fact ' * 180}])+ store.update_system_prompt(scope['session_id'], 'BYTE_STABLE_PREFIX')+ agent._session_db_created = True+ before = agent.session_id+ compressed, prompt = agent._compress_context(messages, 'BYTE_STABLE_PREFIX', force=True, approx_tokens=30000)+ assert len(compressed) < len(messages), (len(compressed), len(messages), [+ dict(operation=e['operation'], keys=[list(m) for m in e['payload'].get('messages', [])])+ for e in store.journal['pending']])+ history = store.get_messages_as_conversation(agent.session_id, include_row_ids=True)+ assert history, 'compaction did not persist history'+ assert before != agent.session_id, 'actual AIAgent rotation did not publish'+ assert store.scope['session_id'] == agent.session_id+ assert agent.tools == frozen_tools+ result = agent.run_conversation('AFTER_FULL_ROTATION', conversation_history=compressed)+ assert not result.get('failed'), result+ history = store.get_messages_as_conversation(agent.session_id, include_row_ids=True)+ store.finish()+ Path(command['receipt']).write_text(json.dumps(dict(before=before, after=agent.session_id,+ history=history, compressed_count=len(compressed), input_count=len(messages), opens=opens,+ fds=writable_fds(), negatives={}, result=result['final_response'])))+ finally:+ agent._end_session_on_close = False+ agent.close()+ store.close()+++if __name__ == '__main__':+ main()diff --git a/tests/gateway/test_worker_rotation_execution.py b/tests/gateway/test_worker_rotation_execution.pynew file mode 100644index 00000000000..933354ef8bb--- /dev/null+++ b/tests/gateway/test_worker_rotation_execution.py@@ -0,0 +1,69 @@+"""Real compression, real registered worker, real ordinary owner transport."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_worker_agent_execution import Model++[email protected]_only+def test_full_agent_worker_rotation_continues_inference_without_canonical_opens(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False},+ 'compression': {'provider': 'custom', 'model': 'worker-model', 'base_url': url}},+ 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc, key):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id=key, source='cli', model='worker-model', toolsets=[])+ assert 'result' in response, response+ return response['result']['session_id']+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid = asyncio.run(create(desc, 'compressed'))+ foreign = asyncio.run(create(desc, 'foreign'))+ receipt = tmp_path / 'receipt.json'+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/rotation_persistence_worker.py')],+ cwd=root, env=env, input=json.dumps(dict(home=str(home), url=url, session_id=sid,+ foreign=foreign, receipt=str(receipt))) + '\n', text=True, capture_output=True, timeout=120)+ assert result.returncode == 0, result.stdout + result.stderr+ proof = json.loads(receipt.read_text())+ assert proof['opens'] == proof['fds'] == [], json.dumps(proof['opens'], indent=2)+ assert proof['compressed_count'] < proof['input_count']+ assert len(peer.requests) == 2, 'summary and continuation must both run'+ assert 'RECOVERY_ACK_WORKER_INFERENCE' in proof['result']+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute('SELECT COUNT(*) FROM session_turn_leases').fetchone()[0] == 0+ assignment = db.execute('SELECT session_id,status FROM worker_executions').fetchone()+ assert assignment == (proof['after'], 'terminal')+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=? AND active=1', (proof['after'],)).fetchone()[0] == len(proof['history'])+ print(json.dumps(dict(before=proof['before'], after=proof['after'], opens=proof['opens'],+ fds=proof['fds'], negatives=proof['negatives'], requests=len(peer.requests),+ compressed_count=proof['compressed_count'], input_count=proof['input_count'],+ persisted_rows=len(proof['history']))))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/state/test_runtime_worker_rotation_automation.py b/tests/state/test_runtime_worker_rotation_automation.pynew file mode 100644index 00000000000..5f58968adfd--- /dev/null+++ b/tests/state/test_runtime_worker_rotation_automation.py@@ -0,0 +1,23 @@+"""Worker rotation carries automation in the publication transaction."""+import json++from tests.state.test_runtime_worker_compression import worker # noqa: F401+++def test_publication_moves_automation_once_and_preserves_cleared_controls(worker):+ db, store = worker+ values = {'goal': {'goal': 'retain objective', 'status': 'paused'},+ 'loop': {'prompt': 'retain loop', 'status': 'active', 'interval_seconds': 60},+ 'heartbeat': {'status': 'active', 'interval_seconds': 120}}+ for family, value in values.items():+ db.set_meta(f'{family}:owned', json.dumps(value))+ assert store.try_acquire_compression_lock('owned', 'compressor')+ store.publish_compression_child(parent_session_id='owned', child_session_id='child', source='cli',+ messages=[{'role': 'assistant', 'content': 'summary'}], compression_lock_holder='compressor')+ for family, value in values.items():+ raw = db.get_meta(f'{family}:child')+ assert raw is not None, family+ assert json.loads(raw)['status'] == value['status']+ assert json.loads(db.get_meta(f'{family}:owned'))['status'] == 'cleared'+ assert json.loads(db.get_meta('goal:child'))['goal'] == values['goal']['goal']+ assert json.loads(db.get_meta('loop:child'))['prompt'] == values['loop']['prompt']