The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: prove local rotation and reset across cold daemon restarts
Tekniumaf3f2dfe1adf
diff --git a/tests/gateway/fixtures/local_lineage_daemon.py b/tests/gateway/fixtures/local_lineage_daemon.pynew file mode 100644index 00000000000..aea436485fe--- /dev/null+++ b/tests/gateway/fixtures/local_lineage_daemon.py@@ -0,0 +1,44 @@+"""Pause only after real rotation/reset publication and durable queued admission."""+import copy+import os+import runpy+import signal+from types import SimpleNamespace++from agent.conversation_compression import _publish_rotated_compaction+from gateway.session_authority import SessionAuthority+from hermes_state_runtime import list_session_admissions++schedule = SessionAuthority._schedule+++def boundary(self, ref):+ pending = list_session_admissions(self.db, session_id=ref.session_id)+ text = pending[-1]['payload'].get('text') if pending else None+ if text in {'RECOVER_RESET', 'FOREIGN_QUEUE'}:+ return+ if text == 'RECOVER_SAFE':+ for logical_id, live in self.sessions.items():+ agent = self.agent(SimpleNamespace(session_id=logical_id))+ if agent is None:+ continue+ if agent.model == 'frozen-reset':+ self.runner.session_store.reset_session(live.route)+ continue+ old = agent.session_id+ holder = 'lineage-fixture'+ assert self.db.try_acquire_compression_lock(old, holder)+ try:+ history = self.db.get_messages_as_conversation(old)+ _publish_rotated_compaction(agent, history, copy.deepcopy(history),+ new_system_prompt=agent._cached_system_prompt or '',+ lease=SimpleNamespace(holder=holder, ttl=300, watermark=None),+ old_session_id=old, compressed_user_turn_outcome='already_present')+ finally:+ self.db.release_compression_lock(old, holder)+ os.kill(os.getpid(), signal.SIGSTOP)+ return schedule(self, ref)+++SessionAuthority._schedule = boundary+runpy.run_module('gateway.run', run_name='__main__')diff --git a/tests/gateway/fixtures/local_lineage_probe.py b/tests/gateway/fixtures/local_lineage_probe.pynew file mode 100644index 00000000000..6fe793cf65b--- /dev/null+++ b/tests/gateway/fixtures/local_lineage_probe.py@@ -0,0 +1,142 @@+"""Separate ordinary daemon restarts after the production physical-target handoff."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket+++def probe(tmp_path):+ root = Path(__file__).resolve().parents[3]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ cfg = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ 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, PYTHONUNBUFFERED='1')+ sessions, params, targets, pids, epochs = {}, {}, {}, [], []+ def db_rows():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return dict(db.execute('SELECT request_id,status FROM session_admissions'))+ async def terminal(request_id):+ async with asyncio.timeout(30):+ while db_rows().get(request_id) != 'terminal':+ await asyncio.sleep(.03)+ async def first(desc, proc):+ async with websocket(home, desc) as ws:+ for name in ('safe', 'reset', 'unknown', 'foreign'):+ cwd = home / name+ cwd.mkdir()+ params[name] = dict(request_id=name, source='gui', cwd=str(cwd), model='frozen-' + name, toolsets=[])+ created = await rpc(ws, 'session.create', **params[name])+ assert 'result' in created, created+ sessions[name] = created['result']['session_id']+ for name, text in [('safe', 'WARM_HISTORY'), ('reset', 'RESET_OLD')]:+ await rpc(ws, 'prompt.submit', session_id=sessions[name], input_id='warm-' + name, text=text)+ await terminal('warm-' + name)+ await rpc(ws, 'prompt.submit', session_id=sessions['unknown'], input_id='started', text='BLOCK_STARTED')+ assert await asyncio.to_thread(peer.blocked.wait, 20)+ await rpc(ws, 'prompt.submit', session_id=sessions['unknown'], input_id='follower', text='NEVER_REPLAY')+ await rpc(ws, 'prompt.submit', session_id=sessions['reset'], input_id='reset', text='RECOVER_RESET')+ await rpc(ws, 'prompt.submit', session_id=sessions['foreign'], input_id='foreign', text='FOREIGN_QUEUE')+ await ws.send(json.dumps({'id': 'crash', 'method': 'prompt.submit', 'params': {+ 'session_id': sessions['safe'], 'input_id': 'safe', 'text': 'RECOVER_SAFE'}}))+ # Wait for the actual publication, not just admission before the fixture ran.+ async with asyncio.timeout(20):+ while True:+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ ended = dict(db.execute('SELECT id,end_reason FROM sessions'))+ if all(ended.get(sessions[n]) == reason for n, reason in+ [('safe', 'compression'), ('reset', 'session_reset'), ('unknown', 'compression')]):+ break+ assert proc.poll() is None+ await asyncio.sleep(.03)+ proc.kill()+ await asyncio.to_thread(proc.wait, 10)+ async def recovered(desc):+ async with websocket(home, desc) as ws:+ for name in ('safe', 'reset'):+ await terminal(name)+ snapshot = await rpc(ws, 'session.resume', session_id=sessions[name])+ assert 'result' in snapshot, snapshot+ history = json.dumps(snapshot['result']['messages'])+ assert 'RECOVERY_ACK_RECOVER_' + name.upper() in history, history+ assert ('RECOVERY_ACK_WARM_HISTORY' in history) == (name == 'safe'), history+ assert 'RESET_OLD' not in history, history+ same = await rpc(ws, 'session.create', **params[name])+ assert same['result']['session_id'] == sessions[name], same+ assert same['result']['info']['model'] == params[name]['model'], same+ assert same['result']['info']['source'] == params[name]['source'], same+ retry = await rpc(ws, 'prompt.submit', session_id=sessions[name], input_id=name,+ text='RECOVER_' + name.upper())+ assert retry['result']['status'] == 'terminal', retry+ unknown = await rpc(ws, 'session.resume', session_id=sessions['unknown'])+ assert [p['status'] for p in unknown['result']['pending']] == ['unknown', 'queued'], unknown+ for name, reason in [('foreign', 'profile_mismatch'), ('fork', 'storage_unavailable')]:+ refusal = await rpc(ws, 'session.resume', session_id=sessions[name])+ assert refusal['error']['message'] == reason, refusal+ try:+ with daemon(root, home, env, barrier=True, fixture='local_lineage_daemon.py') as (proc, desc):+ pids.append(proc.pid); epochs.append(desc['authority_epoch'])+ asyncio.run(first(desc, proc))+ peer.release.set()+ with sqlite3.connect(home / 'state.db') as db:+ for name, sid in sessions.items():+ receipt = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',+ ('gateway.local_policy.v1:' + sid,)).fetchone()[0])+ targets[name] = receipt['entry']['session_id']+ if name != 'foreign':+ assert targets[name] != sid, receipt+ route = json.loads(db.execute("SELECT entry_json FROM gateway_routing WHERE scope='' AND session_key=?",+ (receipt['route'],)).fetchone()[0])+ assert route['session_id'] == targets[name]+ row = db.execute('SELECT cwd FROM sessions WHERE id=?', (targets[name],)).fetchone()+ assert row[0] == params[name]['cwd'], row+ else:+ receipt['profile_id'] = str(user)+ db.execute('UPDATE state_meta SET value=? WHERE key=?',+ (json.dumps(receipt), 'gateway.local_policy.v1:' + sid))+ # A same-origin fork and a copied receipt do not gain the root's authority.+ sessions['fork'] = 'unrelated-fork'+ db.execute("""INSERT INTO sessions(id,source,parent_session_id,model_config,chat_id,user_id,session_key,started_at)+ SELECT ?,source,id,'{"_branch":true}',chat_id,user_id,session_key,started_at FROM sessions WHERE id=?""",+ (sessions['fork'], targets['safe']))+ db.execute('INSERT INTO state_meta(key,value) SELECT ?,value FROM state_meta WHERE key=?',+ ('gateway.local_policy.v1:' + sessions['fork'], 'gateway.local_policy.v1:' + sessions['safe']))+ cfg['model']['default'] = 'changed-default'+ cfg['platform_toolsets']['cli'] = ['terminal']+ (home / 'config.yaml').write_text(json.dumps(cfg))+ for _ in range(2):+ with daemon(root, home, env, barrier=False) as (proc, desc):+ pids.append(proc.pid); epochs.append(desc['authority_epoch'])+ asyncio.run(recovered(desc))+ assert db_rows() == {'warm-safe': 'terminal', 'warm-reset': 'terminal', 'started': 'unknown',+ 'follower': 'queued', 'reset': 'terminal', 'foreign': 'queued', 'safe': 'terminal'}+ texts = [next((m.get('content') for m in reversed(r['messages']) if m['role'] == 'user'), '') for r in peer.requests]+ assert sorted(texts) == sorted(['WARM_HISTORY', 'RESET_OLD', 'BLOCK_STARTED', 'RECOVER_SAFE', 'RECOVER_RESET']), texts+ for name in ('safe', 'reset'):+ request = next(r for r in peer.requests if any(m.get('content') == 'RECOVER_' + name.upper() for m in r['messages']))+ assert request['model'] == params[name]['model'] and not request.get('tools')+ assert params[name]['cwd'] in json.dumps(request['messages']), request['messages']+ return {'pids': pids, 'epochs': epochs, 'logical_ids': sessions, 'physical_targets': targets,+ 'inference_texts': texts, 'stable_receipts': True, 'policy_cwd_history_retained': True,+ 'unknown_not_replayed': True, 'foreign_and_fork_refused': True}+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/fixtures/local_recovery_probe.py b/tests/gateway/fixtures/local_recovery_probe.pyindex 46439f07fa5..2cd05ee9e17 100644--- a/tests/gateway/fixtures/local_recovery_probe.py+++ b/tests/gateway/fixtures/local_recovery_probe.py@@ -61,8 +61,8 @@ def websocket(home, desc):@contextmanager-def daemon(root, home, env, *, barrier):- command = [sys.executable, str(root / 'tests/gateway/fixtures/local_recovery_daemon.py')] if barrier else [sys.executable, '-m', 'gateway.run']+def daemon(root, home, env, *, barrier, fixture='local_recovery_daemon.py'):+ command = [sys.executable, str(root / 'tests/gateway/fixtures' / fixture)] if barrier else [sys.executable, '-m', 'gateway.run']with (home / ('first.log' if barrier else 'restart.log')).open('w+') as log:proc = subprocess.Popen(command, cwd=root, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)try:diff --git a/tests/gateway/test_local_session_lineage.py b/tests/gateway/test_local_session_lineage.pyindex 4d666e866c9..490fe699b79 100644--- a/tests/gateway/test_local_session_lineage.py+++ b/tests/gateway/test_local_session_lineage.py@@ -99,3 +99,9 @@ async def test_local_lineage_transitions_preserve_owner_or_roll_back(tmp_path, mdb.set_meta('gateway.local_policy.v1:unrelated-fork', json.dumps(local_receipt(db, ref.session_id)))with pytest.raises(RuntimeStoreError, match='storage_unavailable'):await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))++[email protected]_only+def test_real_local_lineage_survives_cold_daemon(tmp_path):+ from tests.gateway.fixtures.local_lineage_probe import probe+ print(json.dumps(probe(tmp_path)))