The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(gateway): composed restart/compression/new-session journeys on a real daemon
Teknium441f64afe887
diff --git a/tests/gateway/test_journey_compress_restart_fifo.py b/tests/gateway/test_journey_compress_restart_fifo.pynew file mode 100644index 00000000000..3123ffb1650--- /dev/null+++ b/tests/gateway/test_journey_compress_restart_fifo.py@@ -0,0 +1,223 @@+"""Journey: queued followers -> automatic compression -> gateway restart before drain.++One ordinary daemon (real authority, real SQLite, in-process agent loop, loopback model). A turn's+own preflight compression rotates the transcript while three followers wait behind it; the owner is+stopped before the followers run. After a fresh daemon starts: every admission keeps its identity,+the followers run once each in FIFO order on the compressed transcript, the turn that compressed+is never executed twice, and the compression lineage is the one committed before the restart.+"""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import signal+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket++FOLLOWERS = ('FOLLOWER_1', 'FOLLOWER_2', 'FOLLOWER_3')+++class CompactingModel(BaseHTTPRequestHandler):+ """Summarizes on the `summary` model; the first post-summary turn request parks until released."""++ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ wire = json.dumps(messages)+ text = next((m.get('content', '') for m in reversed(messages) if m['role'] == 'user'), '')+ if messages:+ self.server.requests.append({'model': body.get('model'), 'text': str(text), 'wire': wire})+ if body.get('model') == 'original' and len(wire) > 50000:+ payload = json.dumps({'error': {'message': "This model's maximum context length is 64000 tokens. "+ 'However, your messages resulted in 70000 tokens.',+ 'type': 'invalid_request_error', 'code': 'context_length_exceeded'}}).encode()+ return self._send(400, payload, 'application/json')+ if body.get('model') == 'original' and 'SUMMARY_RETAINED_FACTS' in wire and not self.server.blocked.is_set():+ self.server.blocked.set()+ self.server.release.wait(60)+ # Only the pressure turns are large: the followers must not trigger a second compaction.+ reply = 'SUMMARY_RETAINED_FACTS' if body.get('model') == 'summary' else (+ 'ACK_' + str(text)[:40] + (' ' + 'historical detail ' * 700 if str(text).startswith('PRESSURE_') else ''))+ message = {'role': 'assistant', 'content': reply}+ payload = json.dumps({'id': 'local', 'model': body.get('model'), 'choices': [+ {'index': 0, 'message': message, 'finish_reason': 'stop'}],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()+ kind = 'application/json'+ if body.get('stream'):+ payload = ('data: ' + json.dumps({'id': 'local', 'choices': [+ {'index': 0, 'delta': message, 'finish_reason': 'stop'}]}) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ self._send(200, payload, kind)++ def _send(self, status, payload, kind):+ try:+ self.send_response(status)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass++[email protected]('linux')[email protected]('restart', ['graceful', 'crash'])+def test_followers_survive_compression_and_restart_in_order_exactly_once(tmp_path, restart):+ 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), CompactingModel)+ 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'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url, 'context_length': 64000},+ 'auxiliary': {'title_generation': {'enabled': False},+ 'compression': {'provider': 'custom', 'model': 'summary', 'base_url': url}},+ 'compression': {'protect_first_n': 1, 'protect_last_n': 2, 'threshold_tokens': 12000,+ 'threshold': 0.5, 'in_place': False},+ 'platform_toolsets': {'cli': []}}))+ (home / 'models_dev_cache.json').write_text(json.dumps({'custom': {'id': 'custom', 'models': {+ name: {'id': name, 'name': name, 'limit': {'context': 64000 if name == 'original' else 1000000,+ 'output': 1000}}+ for name in ('original', 'summary')}}}))+ env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url,+ PYTHONUNBUFFERED='1')++ def rows(sql, args=()):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ db.row_factory = sqlite3.Row+ return [dict(row) for row in db.execute(sql, args)]++ def admissions():+ return rows('SELECT admission_id,request_id,target_session_id,status,outcome,seq FROM session_admissions ORDER BY seq')++ def transcript(session_id):+ return [(r['id'], r['role'], r['content']) for r in rows(+ 'SELECT id,role,content FROM messages WHERE session_id=? AND active=1 ORDER BY id', (session_id,))]++ def executed(marker):+ return sum(r['model'] == 'original' and r['text'].startswith(marker) for r in peer.requests)++ before = {}++ async def call(ws, method, **params):+ reply = await rpc(ws, method, **params)+ assert 'result' in reply, reply+ return reply['result']++ async def wait_rows(predicate, timeout=40):+ async with asyncio.timeout(timeout):+ while not predicate():+ await asyncio.sleep(.03)++ async def first(desc, owner):+ async with websocket(home, desc) as ws:+ sid = (await call(ws, 'session.create', source='cli', request_id='journey', model='original',+ provider='custom', base_url=url, toolsets=[], cwd=str(home)))['session_id']+ before['sid'] = sid+ for i in range(12):+ params = dict(session_id=sid, input_id=f'pressure-{i}', text=f'PRESSURE_{i} ' + 'keep these facts ' * 100)+ accepted = await call(ws, 'prompt.submit', **params)+ await wait_rows(lambda: peer.blocked.is_set() or any(+ r['admission_id'] == accepted['admission_id'] and r['status'] == 'terminal' for r in admissions()))+ if peer.blocked.is_set():+ break+ else:+ raise AssertionError('automatic compression never published')+ compacting = params+ children = rows('SELECT id FROM sessions WHERE parent_session_id=?', (sid,))+ assert len(children) == 1, children+ receipts = {compacting['input_id']: accepted['admission_id']}+ for name in FOLLOWERS:+ receipts[name] = (await call(ws, 'prompt.submit', session_id=sid, input_id=name, text=name))['admission_id']+ pending = [r for r in admissions() if r['status'] != 'terminal']+ assert [(r['request_id'], r['status']) for r in pending] == [+ (compacting['input_id'], 'started')] + [(name, 'queued') for name in FOLLOWERS], pending+ before.update(compacting=compacting, receipts=receipts, child=children[0]['id'],+ compacting_requests=executed(compacting['text'][:12]))+ assert sum(r['model'] == 'summary' for r in peer.requests) == 1+ # Restart while the compacted turn is still in flight: nothing behind it may run. A+ # graceful stop interrupts and settles it; a crash leaves it started (-> unknown).+ if restart == 'graceful':+ owner.send_signal(signal.SIGTERM)+ else:+ owner.kill()+ await asyncio.to_thread(owner.wait, 60)+ before['stopped'] = {r['request_id']: (r['status'], r['outcome']) for r in admissions()}+ before['compacted'] = transcript(before['child'])+ peer.release.set()+ assert all(executed(name) == 0 for name in FOLLOWERS), [r['text'] for r in peer.requests]++ async def second(desc):+ sid = before['sid']+ async with websocket(home, desc) as ws:+ resumed = await call(ws, 'session.resume', session_id=sid)+ unknown = [r for r in resumed['pending'] if r['status'] == 'unknown']+ head = before['receipts'][before['compacting']['input_id']]+ if restart == 'crash':+ # Started work that lost its owner is unknown and holds the FIFO; nothing ran yet.+ assert [r['admission_id'] for r in unknown] == [head], resumed['pending']+ assert [r['input_id'] for r in resumed['pending'] if r['status'] == 'queued'] == list(FOLLOWERS)+ assert all(executed(name) == 0 for name in FOLLOWERS)+ else:+ assert before['stopped'][before['compacting']['input_id']] == ('terminal', 'interrupted'), before['stopped']+ assert not unknown, resumed['pending']+ for lost in unknown: # The documented operator step (/discard) for a turn lost in flight.+ await call(ws, 'prompt.resolve_unknown', session_id=sid, admission_id=lost['admission_id'],+ execution_generation=lost['execution_generation'])+ await wait_rows(lambda: all(r['status'] == 'terminal' for r in admissions()))+ for input_id, admission_id in before['receipts'].items():+ text = before['compacting']['text'] if input_id == before['compacting']['input_id'] else input_id+ retried = await call(ws, 'prompt.submit', session_id=sid, input_id=input_id, text=text)+ assert retried['admission_id'] == admission_id, (input_id, retried)+ return await call(ws, 'session.resume', session_id=sid)++ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ asyncio.run(first(desc, owner))+ with daemon(root, home, env, barrier=False) as (_, desc):+ final = asyncio.run(second(desc))+ sid, compacting = before['sid'], before['compacting']+ order = [r['text'] for r in peer.requests if r['model'] == 'original' and r['text'] in FOLLOWERS]+ assert order == list(FOLLOWERS), order+ assert executed(compacting['text'][:12]) == before['compacting_requests'], 'compacted turn replayed'+ for name in FOLLOWERS:+ wire = next(r['wire'] for r in peer.requests if r['text'] == name)+ # protect_first_n keeps PRESSURE_0 verbatim; the compacted middle is only inside the summary.+ turns = [str(m.get('content', '')) for m in json.loads(wire)]+ assert 'SUMMARY_RETAINED_FACTS' in wire and not any(t.startswith('PRESSURE_1 ') for t in turns), name+ settled = admissions()+ assert {r['target_session_id'] for r in settled} == {sid}+ assert [r['request_id'] for r in settled][-3:] == list(FOLLOWERS)+ assert [r['outcome'] for r in settled][-3:] == ['completed'] * 3, settled+ # Compaction state is the one committed before the restart: same single continuation, the root+ # still closed by compression, the summarized transcript a verbatim prefix of the live one.+ assert rows('SELECT id FROM sessions WHERE parent_session_id=?', (sid,)) == [{'id': before['child']}]+ assert rows('SELECT end_reason FROM sessions WHERE id=?', (sid,)) == [{'end_reason': 'compression'}]+ assert any('SUMMARY_RETAINED_FACTS' in str(c) for _, _, c in before['compacted'])+ assert transcript(before['child'])[:len(before['compacted'])] == before['compacted']+ stored = rows("SELECT session_id FROM messages WHERE role='user' AND content IN (?,?,?)", FOLLOWERS)+ assert [r['session_id'] for r in stored] == [before['child']] * 3, stored+ assert sum(r['model'] == 'summary' for r in peer.requests) == 1+ history = json.dumps(final['messages'])+ assert 'SUMMARY_RETAINED_FACTS' in history and all(name in history for name in FOLLOWERS)+ print(json.dumps({'admissions': settled, 'follower_order': order, 'child': before['child']}))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/test_journey_new_session_queued_work.py b/tests/gateway/test_journey_new_session_queued_work.pynew file mode 100644index 00000000000..fdb7e711533--- /dev/null+++ b/tests/gateway/test_journey_new_session_queued_work.py@@ -0,0 +1,154 @@+"""Journey: client `/new` while the earlier session still holds durable queued work.++One ordinary daemon (real authority, SQLite, in-process agent loop, loopback model). The classic CLI+view's own `/new` handler (``hermes_cli.gateway_chat_commands``) runs over a real ``GatewayClient``+while session A has a turn in flight and two followers queued. Documented contract (PR behaviour+change 3): `/new` rebinds only the invoking view; A keeps its FIFO. Asserted:+- B is a fresh canonical session: its own FIFO (it runs while A is blocked), and no A input ever+ reaches B's transcript or B's model requests;+- A's followers stay queued on A, visible in A's snapshot (not B's), and drain on A in order, once;+- another viewer still attached to A stays on A and sees A's completions;+- ``restart``: the owner crashes after `/new`; A's in-flight turn is unknown and holds only A's+ followers (B keeps working); discarding it releases them on A, exactly once.+"""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+from pathlib import Path+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket++A_FOLLOWERS = ('A_FOLLOWER_1', 'A_FOLLOWER_2')++[email protected]('linux')[email protected]('restart', [False, True], ids=['live', 'restart'])+def test_new_session_never_absorbs_or_drops_earlier_queued_work(tmp_path, restart):+ from hermes_cli.gateway_chat_commands import run_command+ from hermes_cli.gateway_chat_view import GatewayChatView+ from hermes_cli.gateway_client import GatewayClient++ 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 = []+ 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'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'view-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}))+ env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')++ def admissions():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ db.row_factory = sqlite3.Row+ return {r['request_id']: dict(r) for r in db.execute(+ 'SELECT request_id,target_session_id,status,outcome,seq FROM session_admissions')}++ def user_turns(session_id):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return [r[0] for r in db.execute("SELECT content FROM messages WHERE session_id=? AND role='user' "+ 'ORDER BY id', (session_id,))]++ def requests():+ return [[m.get('content') for m in r['messages'] if m['role'] == 'user'] for r in peer.requests]++ async def until(predicate, timeout=30):+ async with asyncio.timeout(timeout):+ while not predicate():+ await asyncio.sleep(.03)++ ids = {}++ async def first(desc, owner):+ async with websocket(home, desc) as ws, websocket(home, desc) as other, GatewayClient(ws) as client:+ snapshot = await client.rpc('session.create', request_id='journey-a', source='cli', cwd=str(home),+ model='view-model', provider='custom', base_url=url, toolsets=[])+ view = GatewayChatView(client, snapshot, quiet=True)+ a = ids['a'] = view.session_id+ assert 'result' in await rpc(other, 'session.resume', session_id=a)+ await client.rpc('prompt.submit', session_id=a, input_id='A_HEAD', text='BLOCK_STARTED')+ assert await asyncio.to_thread(peer.blocked.wait, 20)+ for name in A_FOLLOWERS:+ await client.rpc('prompt.submit', session_id=a, input_id=name, text=name)+ assert await run_command(view, '/new', '') is True+ b = ids['b'] = view.session_id+ assert b != a+ # B is its own FIFO: it answers while A's head is still blocked in the model.+ await view.submit('B_TURN')+ await until(lambda: any(r['target_session_id'] == b and r['status'] == 'terminal'+ for r in admissions().values()))+ rows = admissions()+ assert {k: (r['target_session_id'], r['status']) for k, r in rows.items() if k.startswith('A_')} == {+ 'A_HEAD': (a, 'started'), **{n: (a, 'queued') for n in A_FOLLOWERS}}, rows+ b_snapshot = await client.rpc('session.resume', session_id=b)+ a_snapshot = (await rpc(other, 'session.resume', session_id=a))['result']+ assert b_snapshot['pending'] == [] and b_snapshot['messages'][0]['content'] == 'B_TURN', b_snapshot+ assert [r['input_id'] for r in a_snapshot['pending']] == ['A_HEAD', *A_FOLLOWERS], a_snapshot['pending']+ assert requests()[-1] == ['B_TURN'], requests()+ if restart:+ owner.kill()+ await asyncio.to_thread(owner.wait, 10)+ peer.release.set()+ return+ peer.release.set()+ await until(lambda: all(r['status'] == 'terminal' for r in admissions().values()))+ # The viewer that stayed on A saw A's work finish; the /new view was rebound to B only.+ events = (await rpc(other, 'session.events.since', session_id=a, replay_epoch=a_snapshot['replay_epoch'],+ last_sequence=a_snapshot['last_sequence']))['result']['events']+ assert {e.get('payload', {}).get('text') for e in events if e['type'] == 'message.complete'} >= {+ 'RECOVERY_ACK_' + n for n in A_FOLLOWERS}, events+ assert view.session_id == b++ async def second(desc):+ a, b = ids['a'], ids['b']+ async with websocket(home, desc) as ws, GatewayClient(ws) as client:+ a_snapshot = await client.rpc('session.resume', session_id=a)+ lost = [r for r in a_snapshot['pending'] if r['status'] == 'unknown']+ assert [r['input_id'] for r in lost] == ['A_HEAD'], a_snapshot['pending']+ assert [r['input_id'] for r in a_snapshot['pending'] if r['status'] == 'queued'] == list(A_FOLLOWERS)+ # A's unknown head pauses only A: B takes and finishes new work meanwhile.+ await client.rpc('session.resume', session_id=b)+ await client.rpc('prompt.submit', session_id=b, input_id='B_AFTER_RESTART', text='B_AFTER_RESTART')+ await until(lambda: admissions()['B_AFTER_RESTART']['status'] == 'terminal')+ assert all(admissions()[n]['status'] == 'queued' for n in A_FOLLOWERS)+ assert not any(n in sent for sent in requests() for n in A_FOLLOWERS)+ await client.rpc('prompt.resolve_unknown', session_id=a, admission_id=lost[0]['admission_id'],+ execution_generation=lost[0]['execution_generation'])+ await until(lambda: all(r['status'] == 'terminal' for r in admissions().values()))++ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ asyncio.run(first(desc, owner))+ if restart:+ with daemon(root, home, env, barrier=False) as (_, desc):+ asyncio.run(second(desc))+ a, b = ids['a'], ids['b']+ rows = admissions()+ assert all(rows[n]['target_session_id'] == a and rows[n]['outcome'] == 'completed' for n in A_FOLLOWERS), rows+ assert rows['A_HEAD']['outcome'] == ('interrupted' if restart else 'completed'), rows['A_HEAD']+ assert {r['target_session_id'] for k, r in rows.items() if k.startswith('B_') or len(k) == 32} == {b}, rows+ sent = requests()+ assert [s[-1] for s in sent if s[-1] in A_FOLLOWERS] == list(A_FOLLOWERS), sent+ assert sum(s[-1] == 'BLOCK_STARTED' for s in sent) == 1, sent+ b_users = user_turns(b)+ assert b_users == ['B_TURN'] + (['B_AFTER_RESTART'] if restart else []), b_users+ assert not any(t in ('BLOCK_STARTED', *A_FOLLOWERS) for s in sent if 'B_TURN' in s for t in s), sent+ assert [t for t in user_turns(a) if t in A_FOLLOWERS] == list(A_FOLLOWERS)+ print(json.dumps({'restart': restart, 'a': a, 'b': b, 'admissions': rows, 'requests': sent}))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/test_journey_restart_open_prompts.py b/tests/gateway/test_journey_restart_open_prompts.pynew file mode 100644index 00000000000..cb2163fc59f--- /dev/null+++ b/tests/gateway/test_journey_restart_open_prompts.py@@ -0,0 +1,211 @@+"""Journey: restart while one session waits on an approval and another on a clarification.++One ordinary daemon (real authority, SQLite, in-process agent loop with the real terminal and clarify+tools, loopback model). Each session has a turn parked on its prompt and durable followers queued+behind it when the owner goes away. After a fresh daemon starts:+- the stale prompts are gone from every snapshot and answering their old ids is refused, before and+ after the FIFO moves on, and never runs the gated command;+- a crash leaves the parked turn ``unknown`` and holds its followers until /discard (no replay);+ a graceful stop settles it ``interrupted`` and the followers resume on their own;+- every input reaches the model exactly once and only as itself; the gated command never runs.+"""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import shlex+import signal+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket++FOLLOWERS = {'approval': ('APPROVAL_FOLLOWER_1', 'APPROVAL_FOLLOWER_2'),+ 'clarify': ('CLARIFY_FOLLOWER_1', 'CLARIFY_FOLLOWER_2')}+ASK = {'approval': 'ASK_APPROVAL', 'clarify': 'ASK_CLARIFY'}+++class PromptModel(BaseHTTPRequestHandler):+ """ASK_* turns call the gated tool; every other user turn is answered directly."""++ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ last = messages[-1] if messages else {}+ text = next((m.get('content', '') for m in reversed(messages) if m['role'] == 'user'), '')+ if messages:+ self.server.requests.append({'text': str(text), 'after_tool': last.get('role') == 'tool',+ 'users': [m.get('content') for m in messages if m['role'] == 'user']})+ message = {'role': 'assistant', 'content': 'ACK_' + str(text)}+ if last.get('role') == 'user' and text in ASK.values():+ name, args = ('terminal', {'command': self.server.command}) if text == ASK['approval'] else (+ 'clarify', {'questions': [{'question': 'Pick a color', 'choices': ['BLUE', 'GREEN']}]})+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'index': 0, 'id': 'call_' + name, 'type': 'function',+ 'function': {'name': name, 'arguments': json.dumps(args)}}]}+ finish = 'tool_calls' if 'tool_calls' in message else 'stop'+ frame = {'id': 'local', 'model': 'prompt-model', 'choices': [{'index': 0, 'delta': message, 'finish_reason': finish}],+ 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}+ if body.get('stream'):+ payload, kind = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode(), 'text/event-stream'+ else:+ frame['choices'][0]['message'] = frame['choices'][0].pop('delta')+ payload, kind = json.dumps(frame).encode(), 'application/json'+ try:+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass++[email protected]('linux')[email protected]('restart', ['crash', 'graceful'])+def test_restart_fences_open_prompts_and_never_reruns_work(tmp_path, restart):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ target = home / 'gated-removal'+ target.mkdir()+ (target / 'owned.txt').write_text('must survive')+ peer = ThreadingHTTPServer(('127.0.0.1', 0), PromptModel)+ peer.requests = []+ peer.command = 'rm -rf -- ' + shlex.quote(str(target))+ 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': 'prompt-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)},+ 'approvals': {'mode': 'manual', 'timeout': 120}, 'agent': {'clarify_timeout': 120},+ 'platform_toolsets': {'cli': ['terminal', 'clarify']}}))+ env = child_env() | {k: os.environ[k] for k in ('TIRITH_ENABLED',) 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')++ def admissions():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ db.row_factory = sqlite3.Row+ return {r['request_id']: dict(r) for r in db.execute(+ 'SELECT admission_id,request_id,target_session_id,status,outcome,seq FROM session_admissions')}++ def reached(text):+ return sum(r['text'] == text and not r['after_tool'] for r in peer.requests)++ async def call(ws, method, **params):+ reply = await rpc(ws, method, **params)+ assert 'result' in reply, reply+ return reply['result']++ async def until(predicate, timeout=40):+ async with asyncio.timeout(timeout):+ while not predicate():+ await asyncio.sleep(.03)++ async def answer(ws, sid, prompt):+ kind = prompt['kind']+ reply = await rpc(ws, kind + '.respond', session_id=sid, prompt_id=prompt['prompt_id'],+ execution_generation=prompt['execution_generation'],+ **({'choice': 'once'} if kind == 'approval' else {'answer': 'BLUE'}))+ return reply.get('error', {}).get('data', {}).get('reason') or reply.get('error', {}).get('message') or reply['result']++ before = {'sessions': {}, 'prompts': {}}++ async def first(desc, owner):+ async with websocket(home, desc) as ws:+ for kind in ('approval', 'clarify'):+ sid = (await call(ws, 'session.create', source='cli', request_id='journey-' + kind, cwd=str(home),+ model='prompt-model', provider='custom', base_url=url,+ toolsets=['terminal', 'clarify']))['session_id']+ before['sessions'][kind] = sid+ await call(ws, 'prompt.submit', session_id=sid, input_id=ASK[kind], text=ASK[kind])+ prompt = None+ async with asyncio.timeout(30):+ while prompt is None:+ snapshot = await call(ws, 'session.resume', session_id=sid)+ prompt = next((p for p in snapshot['prompts'] if p['kind'] == kind), None)+ await asyncio.sleep(.03)+ before['prompts'][kind] = prompt+ for name in FOLLOWERS[kind]:+ await call(ws, 'prompt.submit', session_id=sid, input_id=name, text=name)+ rows = admissions()+ assert {k: rows[k]['status'] for k in rows} == {+ ASK['approval']: 'started', ASK['clarify']: 'started',+ **{name: 'queued' for names in FOLLOWERS.values() for name in names}}, rows+ assert target.exists()+ if restart == 'graceful':+ owner.send_signal(signal.SIGTERM)+ else:+ owner.kill()+ await asyncio.to_thread(owner.wait, 60)+ before['stopped'] = {k: (r['status'], r['outcome']) for k, r in admissions().items()}++ async def second(desc):+ async with websocket(home, desc) as ws:+ fenced = {}+ for kind, sid in before['sessions'].items():+ snapshot = await call(ws, 'session.resume', session_id=sid)+ assert snapshot['prompts'] == [], snapshot['prompts']+ fenced[kind] = await answer(ws, sid, before['prompts'][kind])+ if restart == 'crash':+ lost = [r for r in snapshot['pending'] if r['status'] == 'unknown']+ assert [r['input_id'] for r in lost] == [ASK[kind]], snapshot['pending']+ queued = [r['input_id'] for r in snapshot['pending'] if r['status'] == 'queued']+ assert queued == list(FOLLOWERS[kind]), snapshot['pending']+ assert fenced == {'approval': 'stale_generation', 'clarify': 'stale_generation'}, fenced+ if restart == 'crash':+ # Unknown work holds the FIFO: nothing ran behind it before the operator decides.+ assert not any(reached(name) for names in FOLLOWERS.values() for name in names)+ for kind, sid in before['sessions'].items():+ snapshot = await call(ws, 'session.resume', session_id=sid)+ lost = next(r for r in snapshot['pending'] if r['status'] == 'unknown')+ await call(ws, 'prompt.resolve_unknown', session_id=sid, admission_id=lost['admission_id'],+ execution_generation=lost['execution_generation'])+ await until(lambda: all(r['status'] == 'terminal' for r in admissions().values()))+ late = {kind: await answer(ws, sid, before['prompts'][kind]) for kind, sid in before['sessions'].items()}+ assert late == {'approval': 'stale_generation', 'clarify': 'stale_generation'}, late+ return {kind: await call(ws, 'session.resume', session_id=sid) for kind, sid in before['sessions'].items()}++ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ asyncio.run(first(desc, owner))+ if restart == 'graceful':+ # A planned stop cancels the parked turns (a decision, not uncertainty); no follower ran.+ assert {before['stopped'][ASK[k]] for k in ASK} == {('terminal', 'interrupted')}, before['stopped']+ else:+ assert {before['stopped'][ASK[k]] for k in ASK} == {('started', None)}, before['stopped']+ assert not any(reached(name) for names in FOLLOWERS.values() for name in names)+ with daemon(root, home, env, barrier=False) as (_, desc):+ final = asyncio.run(second(desc))+ assert target.exists() and (target / 'owned.txt').read_text() == 'must survive'+ for kind, names in FOLLOWERS.items():+ # Exactly once, and only as itself: a lost/cancelled turn never rides a follower's user+ # turn (an unclosed tail would be merged into it and re-sent as part of that request).+ assert reached(ASK[kind]) == 1, [r['text'] for r in peer.requests]+ first_follower = next(r for r in peer.requests if r['text'] == names[0])+ assert first_follower['users'] == [ASK[kind], names[0]], first_follower['users']+ assert not any(r['after_tool'] and r['text'] == ASK[kind] for r in peer.requests), 'gated tool resumed'+ order = [r['text'] for r in peer.requests if r['text'] in names]+ assert order == list(names), order+ history = json.dumps(final[kind]['messages'])+ assert all('ACK_' + name in history for name in names), history[-2000:]+ assert final[kind]['prompts'] == []+ settled = admissions()+ assert all(settled[name]['outcome'] == 'completed' for names in FOLLOWERS.values() for name in names), settled+ print(json.dumps({'restart': restart, 'stopped': before['stopped'], 'settled': settled,+ 'requests': [r['text'] for r in peer.requests]}))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)