The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(hx013): wait for conditions, not the clock, in gateway authority tests
Teknium3793c9fac303
diff --git a/tests/gateway/test_managed_worker_images.py b/tests/gateway/test_managed_worker_images.pyindex 577e5b2addf..c65f0f000ed 100644--- a/tests/gateway/test_managed_worker_images.py+++ b/tests/gateway/test_managed_worker_images.py@@ -50,7 +50,7 @@ def test_admitted_images_reach_managed_worker(tmp_path, mode, model):assert 'result' in accepted, acceptedimage.unlink() # Execution must use retained bytes, never the staging path.async with asyncio.timeout(40):- while True:+ for _ in range(800): # bounded poll; the timeout above is the deadlinereceipt = await rpc(ws, 'prompt.receipt', session_id=sid,admission_id=accepted['result']['admission_id'])if receipt.get('result', {}).get('status') in ('terminal', 'unknown'):diff --git a/tests/gateway/test_multiplex_hot_serve_live.py b/tests/gateway/test_multiplex_hot_serve_live.pyindex 6e22b6b3960..130642a018e 100644--- a/tests/gateway/test_multiplex_hot_serve_live.py+++ b/tests/gateway/test_multiplex_hot_serve_live.py@@ -20,6 +20,8 @@ import timeimport pytestfrom websockets.asyncio.client import connect+from tests.waiting import wait_until+ROOT = Path(__file__).resolve().parents[2]# The daemon is a foreground child of the test (never detached), boots a disposable custom root# with HOME redirected (no systemd unit, no webhook port) and is reaped in every path below.@@ -192,13 +194,15 @@ def kill_recorded_gateway(root, timeout=45):if pid:with contextlib.suppress(ProcessLookupError):os.kill(pid, signal.SIGINT)- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:+ def gone():try:os.kill(pid, 0)except ProcessLookupError:- return- time.sleep(.2)+ return True+ return False+ with contextlib.suppress(AssertionError):+ wait_until(gone, timeout=timeout, interval=.2, what=f'gateway {pid} exited')+ returnwith contextlib.suppress(ProcessLookupError):os.kill(pid, signal.SIGKILL)diff --git a/tests/gateway/test_mutation_prepare_off_loop.py b/tests/gateway/test_mutation_prepare_off_loop.pyindex fc1d2a58351..ddc13141f66 100644--- a/tests/gateway/test_mutation_prepare_off_loop.py+++ b/tests/gateway/test_mutation_prepare_off_loop.py@@ -6,6 +6,8 @@ import timeimport pytest+from tests.waiting import async_wait_until+@pytest.mark.asyncioasync def test_model_prepare_waiting_on_a_contended_writer_keeps_the_loop_live(tmp_path, monkeypatch):@@ -56,22 +58,26 @@ async def test_model_prepare_waiting_on_a_contended_writer_keeps_the_loop_live(tmonkeypatch.setattr(session_mutations, 'mutate_runtime_session', contended)gaps = []+ stopped = asyncio.Event()+async def ticker():+ # A fixed-cadence probe until the test stops it: a gap beyond the tick is a blocked loop.last = time.monotonic()- while True:+ while not stopped.is_set():await asyncio.sleep(0.02)now = time.monotonic()gaps.append(now - last)last = nowtick = asyncio.create_task(ticker())try:- await asyncio.sleep(0.05)+ await async_wait_until(lambda: gaps, timeout=10, what='the loop-stall probe ticking')response = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {'session_id': ref.session_id, 'request_id': 'switch', 'expected_revision': snap['runtime_revision'],'expected_generation': snap['runtime_generation'], 'operation': 'model', 'payload': {'model': 'switched'}}})assert response['result']['model'] == 'switched', responseassert held.is_set() and max(gaps) < 0.5, f'the owner loop stalled {max(gaps):.2f}s behind the prepare writer'finally:+ stopped.set()tick.cancel()release.set()if holder.is_alive():diff --git a/tests/gateway/test_relay_authority.py b/tests/gateway/test_relay_authority.pyindex 4983bdabbb2..04b40fd1537 100644--- a/tests/gateway/test_relay_authority.py+++ b/tests/gateway/test_relay_authority.py@@ -35,6 +35,7 @@ async def probe(peer):from gateway.session_envelope import prepare_native, restore_nativefrom hermes_cli import web_serverfrom hermes_state_runtime import RuntimeStoreError, list_session_admissions+ from tests.waiting import async_wait_untilsockets, outgoing, frames = [], [], []secret = 'owned-relay-fixture-secret'@@ -88,8 +89,9 @@ async def probe(peer):async def send(raw_event):await connector_ws.send(json.dumps({'type': 'inbound', 'event': raw_event,'bufferId': raw_event['message_id']}) + '\n')+ deadline = time.monotonic() + 25async with asyncio.timeout(25):- while True:+ while time.monotonic() < deadline:entries = list(authority.sessions.values())rows = list_session_admissions(authority.db, session_id=next(iter(authority.sessions)),pending_only=False) if entries else []@@ -98,8 +100,9 @@ async def probe(peer):# The drain hands the reply to the adapter only AFTER the terminal commit# (deliver_settled); the entry leaves pending_deliveries once that send# returned. Closing the connector before then drops the final mid-send.- while adapter._active_sessions or settled[0]['admission_id'] in authority.pending_deliveries:- await asyncio.sleep(.01)+ await async_wait_until(lambda: not adapter._active_sessions+ and settled[0]['admission_id'] not in authority.pending_deliveries,+ timeout=25, what='the settled reply handed to the connector')assert any(f.get('type') == 'inbound_ack' and f.get('bufferId') == raw_event['message_id']for f in outgoing), outgoingreturn rows@@ -107,6 +110,7 @@ async def probe(peer):errors = [f for f in outgoing if 'invalid_params' in json.dumps(f) or 'not_found' in json.dumps(f)]assert not errors, errorsawait asyncio.sleep(.02)+ raise TimeoutError(f"{raw_event['message_id']} never settled")try:failed_insert = asyncio.Event()@@ -171,17 +175,14 @@ async def probe(peer):queued.update(message_id='relay-4', text='QUEUED_AFTER_BLOCK')await connector_ws.send(json.dumps({'type': 'inbound', 'event': queued}) + '\n')try:- async with asyncio.timeout(5):- while not any(r['request_id'] == 'relay-4' for r in list_session_admissions(- authority.db, session_id=sid, pending_only=False)):- await asyncio.sleep(.01)+ await async_wait_until(lambda: any(r['request_id'] == 'relay-4' for r in list_session_admissions(+ authority.db, session_id=sid, pending_only=False)), timeout=5, what='relay-4 admitted')assert not adapter._pending_messagesfinally:peer.release.set()- async with asyncio.timeout(10):- while any(not task.done() for task in adapter._background_tasks) or any(r['status'] != 'terminal' for r in- list_session_admissions(authority.db, session_id=sid, pending_only=False)) or authority.pending_deliveries:- await asyncio.sleep(.01)+ await async_wait_until(lambda: not (any(not task.done() for task in adapter._background_tasks) or any(+ r['status'] != 'terminal' for r in list_session_admissions(authority.db, session_id=sid, pending_only=False))+ or authority.pending_deliveries), timeout=10, what='every relay admission settled and delivered')rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)assert len(peer.requests) == 4, peer.requestspayload = rows[0]['payload']@@ -237,9 +238,7 @@ async def probe(peer):# 4401 must revoke queued provenance, not grant on a cached descriptor.revoke = Trueawait connector_ws.close(code=4401, reason='revoked')- async with asyncio.timeout(5):- while not transport.auth_revoked:- await asyncio.sleep(.01)+ await async_wait_until(lambda: transport.auth_revoked, timeout=5, what='the connector auth revoked')try:restore_native(payload, runner)except RuntimeStoreError:diff --git a/tests/gateway/test_retire_settles_waiters.py b/tests/gateway/test_retire_settles_waiters.pyindex 0e676c34a3b..9e7f2c1134f 100644--- a/tests/gateway/test_retire_settles_waiters.py+++ b/tests/gateway/test_retire_settles_waiters.py@@ -9,6 +9,7 @@ from gateway import run_runtimefrom hermes_state_runtime import RuntimeStoreError, list_session_admissionsfrom tests.gateway.test_profile_retire_stops_turns import ACTOR, REF, _Agent, _authorityfrom gateway.session_contract import Submission+from tests.waiting import async_wait_until@pytest.mark.asyncio@@ -44,5 +45,6 @@ async def test_successful_retirement_fails_pending_waiters_and_keeps_rows_queuedassert rows['follower']['status'] == 'queued' # durable: the next owner runs itfinally:agent.release.set()- await asyncio.sleep(.05)+ await async_wait_until(lambda: all(task.done() for task in run_runtime._authority_tasks(authority)),+ timeout=10, what="the authority's tasks finished")db.close()diff --git a/tests/gateway/test_session_mutation_compress.py b/tests/gateway/test_session_mutation_compress.pyindex 8a04710b2fe..ac280d62e32 100644--- a/tests/gateway/test_session_mutation_compress.py+++ b/tests/gateway/test_session_mutation_compress.py@@ -10,6 +10,7 @@ import threadingimport pytestfrom tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocketfrom tests.gateway.test_session_mutation_model import CatalogModel+from tests.waiting import async_wait_untilclass SummaryModel(CatalogModel):@@ -87,13 +88,12 @@ def run_compress_case(tmp_path, mode, in_place):accepted = {}async def turn(text):accepted[text] = await call('prompt.submit', session_id=sid, input_id=text, text=text)- async with asyncio.timeout(30):- while True:- with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:- row = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()- if row and row[0] == 'terminal':- return await call('session.resume', session_id=sid)- await asyncio.sleep(.03)+ def terminal():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ row = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()+ return row and row[0] == 'terminal'+ await async_wait_until(terminal, timeout=30, what=f'{text} terminal')+ return await call('session.resume', session_id=sid)history_count = 16for i in range(history_count):before = await turn('HISTORY_' + str(i))diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.pyindex 2f88bc6ae64..05043f3fedc 100644--- a/tests/gateway/test_session_mutation_model.py+++ b/tests/gateway/test_session_mutation_model.py@@ -7,6 +7,8 @@ from pathlib import Pathimport sqlite3import threading+from tests.waiting import async_wait_until+import pytestfrom tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket@@ -52,13 +54,12 @@ def test_model_receipt_changes_next_wire_and_branch_keeps_independent_history(tmreturn response['result']async def turn(sid, text):await call('prompt.submit', session_id=sid, input_id=text, text=text)- async with asyncio.timeout(30):- while True:- with sqlite3.connect(home / 'state.db') as db:- status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()- if status and status[0] == 'terminal':- return await call('session.resume', session_id=sid)- await asyncio.sleep(.03)+ def terminal():+ with sqlite3.connect(home / 'state.db') as db:+ status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()+ return status and status[0] == 'terminal'+ await async_wait_until(terminal, timeout=30, what=f'{text} terminal')+ return await call('session.resume', session_id=sid)sid = (await call('session.create', source='cli', request_id='owner', toolsets=[]))['session_id']before = await turn(sid, 'ORIGINAL_HISTORY')params = dict(session_id=sid, request_id='switch', operation='model', payload={'model': 'switched'},@@ -114,7 +115,6 @@ async def test_input_queued_while_a_model_receipt_commits_still_runs(tmp_path, m"""A drain that runs while the model receipt commits off-loop sees the new stored policy besidethe old live one and pauses; publishing the policy must wake it, or the input stays queueduntil another submit or a restart."""- import timefrom types import SimpleNamespacefrom gateway import runfrom gateway.config import GatewayConfig@@ -145,23 +145,30 @@ async def test_input_queued_while_a_model_receipt_commits_still_runs(tmp_path, mref = create_local_session(authority, owner.actor, dict(request_id='m', source='cli', cwd=str(tmp_path),model='frozen', toolsets=[]))# A contended receipt transaction: the commit thread holds it open while the loop runs.- entered = threading.Event()- db._conn.create_function('hold_receipt', 1, lambda s: (entered.set(), time.sleep(s))[1] or 0)+ entered, release = threading.Event(), threading.Event()+ db._conn.create_function('hold_receipt', 1, lambda s: (entered.set(), release.wait(s))[1] and 0)db._execute_write(lambda c: c.execute("CREATE TRIGGER hold_receipt AFTER INSERT ON state_meta "- "WHEN NEW.key LIKE 'gateway.mutation.v1.%' BEGIN SELECT hold_receipt(0.4); END"))+ "WHEN NEW.key LIKE 'gateway.mutation.v1.%' BEGIN SELECT hold_receipt(30); END"))snap = db.get_session(ref.session_id)try:mutation = asyncio.create_task(owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {'session_id': ref.session_id, 'request_id': 'switch', 'expected_revision': snap['runtime_revision'],'expected_generation': snap['runtime_generation'], 'operation': 'model', 'payload': {'model': 'switched'}}}))await asyncio.to_thread(entered.wait, 5)- queued = await authority.submit(owner.actor, Submission('during-switch', ref, {'text': 'FOLLOWER'}, 'queue'))+ # The follower is submitted while the receipt transaction is still open: hold it until+ # that submit is parked behind the session's mutation lock.+ submit = asyncio.create_task(authority.submit(owner.actor, Submission('during-switch', ref, {'text': 'FOLLOWER'}, 'queue')))+ lock = authority.sessions[ref.session_id].mutation_lock+ await async_wait_until(lambda: getattr(lock, '_waiters', None), timeout=10, what='the follower submit queued')+ release.set()+ queued = await submitassert (await mutation)['result']['model'] == 'switched'- async with asyncio.timeout(10):- while rt.get_session_admission(db, admission_id=queued.admission_id)['status'] != 'terminal':- await asyncio.sleep(0.05)+ await async_wait_until(+ lambda: rt.get_session_admission(db, admission_id=queued.admission_id)['status'] == 'terminal',+ timeout=10, what='the queued follower ran after the policy was published')assert executed == ['FOLLOWER']finally:+ release.set()await owner.close()store.close_all_db_handles()diff --git a/tests/gateway/test_terminal_commit_crash.py b/tests/gateway/test_terminal_commit_crash.pyindex e46882e5291..912d8d516b3 100644--- a/tests/gateway/test_terminal_commit_crash.py+++ b/tests/gateway/test_terminal_commit_crash.py@@ -11,6 +11,7 @@ import threadingimport aiohttpimport pytestfrom tests.gateway.fixtures.local_recovery_probe import daemon, Model+from tests.waiting import async_wait_until@pytest.mark.platforms("linux")@@ -61,9 +62,7 @@ def test_terminal_commit_before_publication_survives_kill(tmp_path):follower = await response.json()assert response.status == 202, followerpeer.release.set()- async with asyncio.timeout(30):- while snapshot()[1] is None:- await asyncio.sleep(.02)+ await async_wait_until(lambda: snapshot()[1] is not None, timeout=30, what='the terminal result committed')rows, saved = snapshot()assert not pending.done(), 'HTTP result published before crash barrier'proc.kill(); await asyncio.to_thread(proc.wait, 10)@@ -78,9 +77,7 @@ def test_terminal_commit_before_publication_survives_kill(tmp_path):reply = await response.json()assert response.status == 200, replyassert reply['choices'][0]['message']['content'] == saved['result']['final_response']- async with asyncio.timeout(25):- while snapshot()[0][follower] != 'terminal':- await asyncio.sleep(.03)+ await async_wait_until(lambda: snapshot()[0][follower] == 'terminal', timeout=25, what='the follower ran after restart')assert snapshot()[0]['once'] == 'terminal'assert snapshot()[1] == saveddiff --git a/tests/gateway/test_worker_lifecycle_execution.py b/tests/gateway/test_worker_lifecycle_execution.pyindex d53edaaf2bd..c879cb7587d 100644--- a/tests/gateway/test_worker_lifecycle_execution.py+++ b/tests/gateway/test_worker_lifecycle_execution.py@@ -15,6 +15,7 @@ import pytestfrom tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocketfrom tests.gateway.test_worker_agent_execution import Model+from tests.waiting import async_wait_until@pytest.mark.platforms("linux")@@ -56,13 +57,11 @@ def test_worker_lifecycle_then_owner_successor_refuses_late_mutations(tmp_path):assert 'result' in resumed, resumedresponse = await rpc(ws, 'prompt.submit', session_id=sid, input_id='successor', text='SUCCESSOR')assert 'result' in response, response- async with asyncio.timeout(30):- while True:- with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:- status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', ('successor',)).fetchone()- if status and status[0] == 'terminal':- return- await asyncio.sleep(.05)+ def terminal():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', ('successor',)).fetchone()+ return status and status[0] == 'terminal'+ await async_wait_until(terminal, timeout=30, what='the successor admission terminal')try:with daemon(root, home, env, barrier=False) as (_, desc):sid, foreign = asyncio.run(create(desc))diff --git a/tests/test_session_daemon_reaper.py b/tests/test_session_daemon_reaper.pyindex be668739ebc..23f839de508 100644--- a/tests/test_session_daemon_reaper.py+++ b/tests/test_session_daemon_reaper.py@@ -8,12 +8,12 @@ from __future__ import annotationsimport osimport subprocessimport sys-import timefrom types import SimpleNamespaceimport pytestfrom tests import conftest as suite_conftest+from tests.waiting import wait_untildef _detached(env_home, marker):@@ -32,7 +32,9 @@ def test_session_teardown_terminates_daemons_under_the_session_basetemp_only(tmpinside = _detached(basetemp / "t0" / "hermes", "inside")outside = _detached(elsewhere, "outside")try:- time.sleep(0.3)+ # Both children have exec'd with their HERMES_HOME (what the reaper reads from /proc).+ wait_until(lambda: {inside.pid, outside.pid} <= set(suite_conftest._processes_with_hermes_home_under(+ [basetemp, elsewhere])), timeout=10, what='both detached children started')config = SimpleNamespace(_tmp_path_factory=SimpleNamespace(_basetemp=basetemp))reaped = suite_conftest._reap_session_hermes_processes(config)assert inside.pid in reaped and outside.pid not in reaped