The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(hx013): wait for conditions, not the clock, in gateway worker tests
Teknium385e9b89a5bc
diff --git a/tests/gateway/test_managed_worker_checkpoint_limits.py b/tests/gateway/test_managed_worker_checkpoint_limits.pyindex bd563351ae0..680b6166df5 100644--- a/tests/gateway/test_managed_worker_checkpoint_limits.py+++ b/tests/gateway/test_managed_worker_checkpoint_limits.py@@ -13,6 +13,7 @@ import threadingimport pytestfrom tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket+from tests.waiting import async_wait_untilclass Model(BaseHTTPRequestHandler):@@ -80,9 +81,8 @@ def test_managed_worker_trims_checkpoints_to_the_configured_max_snapshots(tmp_pafor request_id in ('first', 'second'):submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text='WRITE')assert 'result' in submitted, submitted- async with asyncio.timeout(90):- while status(request_id) != [('terminal',)]:- await asyncio.sleep(.05)+ await async_wait_until(lambda: status(request_id) == [('terminal',)], timeout=90, interval=.05,+ what=request_id + ' terminal')with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:return db.execute('SELECT COUNT(*) FROM worker_executions WHERE session_id=?', (sid,)).fetchone()[0]try:diff --git a/tests/gateway/test_managed_worker_launch.py b/tests/gateway/test_managed_worker_launch.pyindex 10f4414e35a..681040f79a4 100644--- a/tests/gateway/test_managed_worker_launch.py+++ b/tests/gateway/test_managed_worker_launch.py@@ -8,10 +8,12 @@ from pathlib import Pathimport sqlite3import sysimport threading+import timeimport pytestfrom tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.waiting import async_wait_untilclass Model(BaseHTTPRequestHandler):@@ -153,13 +155,14 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathassert 'result' in submitted, submittedif peer.control_mode:async def prompt(kind):- async with asyncio.timeout(20):- while True:- snapshot = await rpc(ws, 'session.resume', session_id=sid)- found = next((p for p in snapshot['result']['prompts'] if p['kind'] == kind), None)- if found:- return found- await asyncio.sleep(.05)+ deadline = time.monotonic() + 20+ while True:+ snapshot = await rpc(ws, 'session.resume', session_id=sid)+ found = next((p for p in snapshot['result']['prompts'] if p['kind'] == kind), None)+ if found:+ return found+ assert time.monotonic() < deadline, ('no open ' + kind + ' prompt', snapshot)+ await asyncio.sleep(.05)approval = await prompt('approval')assert target.exists()answered = await rpc(ws, 'approval.respond', session_id=sid,@@ -172,9 +175,8 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathexecution_generation=clarify['execution_generation'])assert 'result' in stopped, stoppedpeer.release.set()- async with asyncio.timeout(15):- while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) == [('started',)]:- await asyncio.sleep(.05)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (+ 'managed-input',)) != [('started',)], timeout=15, interval=.05, what='stopped turn settled')assert query('SELECT status FROM session_admissions') == [('terminal',)], (home / 'restart.log').read_text()returnanswered = await rpc(ws, 'clarify.respond', session_id=sid,@@ -196,9 +198,8 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathfollower = await rpc(ws, 'prompt.submit', session_id=sid, input_id='follower', text='NEVER_REPLAY')assert 'result' in follower, followerchildren[0].kill()- async with asyncio.timeout(10):- while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) == [('started',)]:- await asyncio.sleep(.05)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (+ 'managed-input',)) != [('started',)], timeout=10, interval=.05, what='killed worker turn unknown')assert query('SELECT request_id,status FROM session_admissions ORDER BY seq') == [('managed-input', 'unknown'), ('follower', 'queued')]restored = await rpc(ws, 'session.resume', session_id=sid)@@ -210,9 +211,8 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path# Viewer connection is gone while the real model still holds the turn.assert psutil.Process(pid).is_running()peer.release.set()- async with asyncio.timeout(40):- while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) != [('terminal',)]:- await asyncio.sleep(.05)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (+ 'managed-input',)) == [('terminal',)], timeout=40, interval=.05, what='managed turn terminal')async with websocket(home, desc) as ws:restored = await rpc(ws, 'session.resume', session_id=sid)history = restored['result']['messages']@@ -248,9 +248,9 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path# The next admission's worker adopts it from the profile checkpoint (process_manage).assert started['pid'] in [e['pid'] for e in json.loads((home / 'processes.json').read_text())]gate.touch()- async with asyncio.timeout(10):- while psutil.pid_exists(background.pid) and psutil.Process(background.pid).status() != psutil.STATUS_ZOMBIE:- await asyncio.sleep(.05)+ await async_wait_until(lambda: not psutil.pid_exists(background.pid)+ or psutil.Process(background.pid).status() == psutil.STATUS_ZOMBIE,+ timeout=10, interval=.05, what='background process exited')else:assert any(role == 'tool' and 'MANAGED_TOOL_EFFECT' in content for role, content in rows), rowsassert query('SELECT status FROM worker_executions WHERE session_id=?', (sid,)) == [('terminal',)]@@ -272,9 +272,8 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathawait rpc(ws, 'session.resume', session_id=sid)next_turn = await rpc(ws, 'prompt.submit', session_id=sid, input_id='history', text='RESUME_HISTORY')assert 'result' in next_turn, next_turn- async with asyncio.timeout(30):- while query('SELECT status FROM session_admissions WHERE request_id=?', ('history',)) != [('terminal',)]:- await asyncio.sleep(.05)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (+ 'history',)) == [('terminal',)], timeout=30, interval=.05, what='history turn terminal')restored = await rpc(ws, 'session.resume', session_id=sid)assert 'MANAGED_HISTORY_DONE' in json.dumps(restored['result']['messages']), restoredrequest = peer.requests[-1]diff --git a/tests/gateway/test_managed_worker_lineage.py b/tests/gateway/test_managed_worker_lineage.pyindex 1ee930fb5e6..7c88c1d89eb 100644--- a/tests/gateway/test_managed_worker_lineage.py+++ b/tests/gateway/test_managed_worker_lineage.py@@ -10,6 +10,7 @@ import threadingimport pytestfrom tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket+from tests.waiting import async_wait_until@pytest.mark.parametrize(('mode', 'invariant'), [@@ -49,11 +50,15 @@ def test_worker_lineage_and_settlement(tmp_path, mode, invariant):return reply['result']async def settled(ws, sid, input_id):- async with asyncio.timeout(45):- while query('SELECT status FROM session_admissions WHERE request_id=?', (input_id,)) != [('terminal',)]:- await asyncio.sleep(.005)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (+ input_id,)) == [('terminal',)], timeout=45, interval=.005, what=input_id + ' terminal')return await call(ws, 'session.resume', session_id=sid)+ def unwound():+ # What reset/rewind fence on: no live worker and no transcript turn lease left behind.+ return (not query("SELECT 1 FROM worker_executions WHERE status!='terminal'")+ and not query('SELECT 1 FROM session_turn_leases'))+async def mutate(ws, sid, request_id, operation, payload):snap = await call(ws, 'session.resume', session_id=sid)return await call(ws, 'session.mutate', session_id=sid, request_id=request_id,@@ -68,9 +73,8 @@ def test_worker_lineage_and_settlement(tmp_path, mode, invariant):sid = created['session_id']first = await call(ws, 'prompt.submit', session_id=sid, input_id='before', text='BEFORE_RESET')if invariant == 'initialization':- async with asyncio.timeout(30):- while query('SELECT status FROM session_admissions') != [('unknown',)]:- await asyncio.sleep(.02)+ await async_wait_until(lambda: query('SELECT status FROM session_admissions') == [('unknown',)],+ timeout=30, interval=.02, what='failed worker admission unknown')assert peer.requests == []errors = (home / 'logs/errors.log').read_text()assert 'Managed worker lost: managed_worker_failed' in errors@@ -90,7 +94,7 @@ def test_worker_lineage_and_settlement(tmp_path, mode, invariant):assert duplicate['admission_id'] == first['admission_id']return# Base's broken finish handshake needs to unwind before the independent reset probe.- await asyncio.sleep(.5)+ await async_wait_until(unwound, timeout=30, what='finished worker and turn lease released')reset = await mutate(ws, sid, 'reset', 'reset', {})target = reset['target_session_id']await call(ws, 'prompt.submit', session_id=sid, input_id='after', text='AFTER_RESET')@@ -103,7 +107,7 @@ def test_worker_lineage_and_settlement(tmp_path, mode, invariant):if mode != 'normal':assert query("SELECT json_extract(lineage_json,'$[#-1]') FROM session_admissions WHERE request_id='after'") == [(target,)]else:- await asyncio.sleep(.5)+ await async_wait_until(unwound, timeout=30, what='finished worker and turn lease released')rows = query("SELECT id FROM messages WHERE session_id=? AND role='user'", (target,))assert rows, snaprewound = await mutate(ws, sid, 'rewind', 'rewind', {'target_message_id': rows[-1][0]})diff --git a/tests/gateway/test_managed_worker_no_delegation.py b/tests/gateway/test_managed_worker_no_delegation.pyindex d185eb5fc66..ae5bd50f188 100644--- a/tests/gateway/test_managed_worker_no_delegation.py+++ b/tests/gateway/test_managed_worker_no_delegation.py@@ -13,6 +13,7 @@ import threadingimport pytestfrom tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.waiting import async_wait_untilclass Model(BaseHTTPRequestHandler):@@ -69,9 +70,8 @@ def test_managed_worker_turn_does_not_offer_delegate_task(tmp_path):sid = session['result']['session_id']submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='run', text='hello')assert 'result' in submitted, submitted- async with asyncio.timeout(90):- while rows("SELECT status FROM session_admissions WHERE request_id='run'") != [('terminal',)]:- await asyncio.sleep(.1)+ await async_wait_until(lambda: rows("SELECT status FROM session_admissions WHERE request_id='run'") == [+ ('terminal',)], timeout=90, interval=.1, what='run terminal')try:with daemon(root, home, env, barrier=False) as (_owner, desc):asyncio.run(exercise(desc))diff --git a/tests/gateway/test_native_reply_crash_recovery.py b/tests/gateway/test_native_reply_crash_recovery.pyindex a5ad66cdf76..9588d716790 100644--- a/tests/gateway/test_native_reply_crash_recovery.py+++ b/tests/gateway/test_native_reply_crash_recovery.py@@ -78,7 +78,7 @@ def _owner(tmp_path):crashed = status()[marker]with daemon(root, home, env, barrier=False):wait_for(lambda: status().get(marker) != 'started', diagnostic)- time.sleep(3) # a (second) delivery would arrive inside this window+ time.sleep(3) # health: allow HX013 -- proves NO (second) delivery arrives in this window; absence has no eventprompts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user')for r in model.requests]return crashed, len(replies('RECOVERY_ACK_' + marker)), sum(marker in p for p in prompts)diff --git a/tests/gateway/test_profile_retire_stops_turns.py b/tests/gateway/test_profile_retire_stops_turns.pyindex a6566a96ab2..fbdcb7ff9eb 100644--- a/tests/gateway/test_profile_retire_stops_turns.py+++ b/tests/gateway/test_profile_retire_stops_turns.py@@ -15,6 +15,7 @@ from gateway.session_authority import LiveSession, SessionAuthorityfrom gateway.session_contract import Principal, SessionRef, Submissionfrom hermes_state import SessionDBfrom hermes_state_runtime import begin_runtime_epoch, list_session_admissions+from tests.waiting import async_wait_untilACTOR = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')REF = SessionRef('owned', 's')@@ -93,7 +94,8 @@ async def test_unserve_stops_and_joins_the_running_turn_before_release(tmp_path,assert retired is False and not returned.is_set()finally:agent.release.set()- await asyncio.sleep(.05)+ if agent.started.is_set(): # the released turn hands its result back before the store closes+ await async_wait_until(returned.is_set, timeout=10, what='turn returned')db.close()@@ -128,5 +130,6 @@ async def test_retire_stops_the_turn_a_hosted_room_stop_waits_for(tmp_path, monkassert retired is True and returned.is_set()finally:agent.release.set()- await asyncio.sleep(.05)+ if agent.started.is_set(): # the released turn hands its result back before the store closes+ await async_wait_until(returned.is_set, timeout=10, what='turn returned')db.close()diff --git a/tests/gateway/test_session_a2a.py b/tests/gateway/test_session_a2a.pyindex c2b7685efac..2e086503978 100644--- a/tests/gateway/test_session_a2a.py+++ b/tests/gateway/test_session_a2a.py@@ -181,7 +181,7 @@ async def test_forward_wakes_on_the_completion_frame_instead_of_a_fixed_100ms_po'status': 'terminal' if done else 'queued', 'admission_id': 'adm', 'outcome': 'completed'}}))if len(calls) == 1:async def complete():- await asyncio.sleep(1.0)+ await asyncio.sleep(1.0) # health: allow HX013 -- the fake turn's 1 s length is the window the RPC-count bound is measured overawait ws.send(json.dumps({'jsonrpc': '2.0', 'method': 'event', 'params': {'type': 'message.complete', 'session_id': 's', 'payload': {'admission_id': 'adm'}}}))asyncio.ensure_future(complete())diff --git a/tests/gateway/test_session_read_commands.py b/tests/gateway/test_session_read_commands.pyindex 32e95f9472c..59257b3149a 100644--- a/tests/gateway/test_session_read_commands.py+++ b/tests/gateway/test_session_read_commands.py@@ -7,6 +7,7 @@ from pathlib import Pathimport signalimport subprocessimport threading+import timeimport pytest@@ -43,13 +44,14 @@ def test_local_session_reads_report_this_session_and_refuse_their_write_forms(tmcreated = await rpc(ws, 'session.create', request_id='reads', source='cli', toolsets=[], cwd=str(work))sid = created['result']['session_id']await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_READS')- async with asyncio.timeout(45):- while True:- snap = (await rpc(ws, 'session.resume', session_id=sid))['result']- if not snap['running'] and not snap['pending'] and 'RECOVERY_ACK_WARM_READS' in json.dumps(- snap['messages']):- break- await asyncio.sleep(.1)+ deadline = time.monotonic() + 45+ while True:+ snap = (await rpc(ws, 'session.resume', session_id=sid))['result']+ if not snap['running'] and not snap['pending'] and 'RECOVERY_ACK_WARM_READS' in json.dumps(+ snap['messages']):+ break+ assert time.monotonic() < deadline, ('warm turn never settled', snap)+ await asyncio.sleep(.1)for command in ('usage', 'insights', 'profile', 'topup', 'diff', 'memory', 'kanban list','suggestions', 'bundles', 'usage reset', 'memory approval on', 'kanban create x','suggestions catalog', 'debug', 'agents', 'sessions', 'platform', 'fast'):diff --git a/tests/gateway/test_worker_compression_admission.py b/tests/gateway/test_worker_compression_admission.pyindex 11f7b6d9c2b..c09965d9cee 100644--- a/tests/gateway/test_worker_compression_admission.py+++ b/tests/gateway/test_worker_compression_admission.py@@ -6,10 +6,12 @@ import jsonfrom pathlib import Pathimport sqlite3import threading+import timeimport pytestfrom tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket+from tests.waiting import async_wait_untilclass OverflowModel(BaseHTTPRequestHandler):@@ -115,13 +117,14 @@ def test_automatic_worker_rotation_retains_retry_identity_and_fifo(tmp_path, endfor i in range(12):params = dict(session_id=sid, input_id=f'pressure-{i}', text='HISTORY_' + str(i) + ' preserve these facts ' * 100)accepted = await call('prompt.submit', **params)- async with asyncio.timeout(40):- while True:- admission = rows('SELECT * FROM session_admissions WHERE admission_id=?', (accepted['admission_id'],))[0]- children = rows('SELECT id FROM sessions WHERE parent_session_id=?', (sid,))- if children or admission['status'] in ('terminal', 'unknown'):- break- await asyncio.sleep(.03)+ deadline = time.monotonic() + 40+ while True:+ admission = rows('SELECT * FROM session_admissions WHERE admission_id=?', (accepted['admission_id'],))[0]+ children = rows('SELECT id FROM sessions WHERE parent_session_id=?', (sid,))+ if children or admission['status'] in ('terminal', 'unknown'):+ break+ assert time.monotonic() < deadline, dict(admission)+ await asyncio.sleep(.03)if not children:assert admission['status'] == 'terminal', admissioncontinue@@ -146,9 +149,8 @@ def test_automatic_worker_rotation_retains_retry_identity_and_fifo(tmp_path, endpeer.release.set()# Follower turn = a fresh worker process + one inference; on a loaded runner# (40 parallel test files) that has taken >45 s.- async with asyncio.timeout(120):- while rows("SELECT status FROM session_admissions WHERE request_id='follower'")[0]['status'] != 'terminal':- await asyncio.sleep(.03)+ await async_wait_until(lambda: rows("SELECT status FROM session_admissions WHERE request_id='follower'")[0][+ 'status'] == 'terminal', timeout=120, interval=.03, what='follower terminal')assert rows("SELECT status FROM session_admissions WHERE status!='terminal'") == []assert rows("SELECT status FROM worker_executions WHERE status!='terminal'") == []snapshot = await call('session.resume', session_id=sid)