The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(hx013): wait for conditions, not the clock, in gateway session tests
Tekniuma98adf3d6184
diff --git a/tests/gateway/test_api_responses_stream_retry.py b/tests/gateway/test_api_responses_stream_retry.pyindex c174620ad78..703e0da360c 100644--- a/tests/gateway/test_api_responses_stream_retry.py+++ b/tests/gateway/test_api_responses_stream_retry.py@@ -98,9 +98,8 @@ async def test_a_different_body_under_an_in_flight_key_is_refused_and_the_first_async with TestClient(TestServer(app)) as client:seed = await (await client.post('/v1/responses', json={'input': 'seed'})).json()first = asyncio.ensure_future(client.post('/v1/responses', json={'input': 'first'}, headers=headers))- async with asyncio.timeout(10):- while 'first' not in calls:- await asyncio.sleep(0.02)+ from tests.waiting import async_wait_until+ await async_wait_until(lambda: 'first' in calls, timeout=10, what="the first request's turn to start")other = await client.post('/v1/responses', json={'input': 'other', 'previous_response_id': seed['id']},headers=headers)other_body = await other.json()diff --git a/tests/gateway/test_managed_worker_reader_thread.py b/tests/gateway/test_managed_worker_reader_thread.pyindex 974ae36acba..7b1deccdd2c 100644--- a/tests/gateway/test_managed_worker_reader_thread.py+++ b/tests/gateway/test_managed_worker_reader_thread.py@@ -8,9 +8,21 @@ import sysimport pytest+from tests.waiting import async_wait_until+SILENT = 'import sys; sys.stdin.buffer.read()'+def _parked(worker):+ """The worker's reader thread is blocked inside ``read_frame`` on the silent pipe."""+ frame = worker.reader and sys._current_frames().get(worker.reader.ident)+ while frame is not None:+ if frame.f_code.co_name == 'read_frame':+ return True+ frame = frame.f_back+ return False++def _spawn(code):return subprocess.Popen([sys.executable, '-c', code], stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)@@ -25,7 +37,8 @@ def test_parked_worker_reads_leave_the_default_executor_free():asyncio.get_running_loop().set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=4))parked = [asyncio.create_task(w.next_frame(None, ack=30)) for w in workers]try:- await asyncio.sleep(.3)+ await async_wait_until(lambda: all(_parked(w) for w in workers), timeout=10,+ what='every reader parked on its silent pipe')# Settlement, env preparation and control RPCs all run on this pool.return await asyncio.wait_for(asyncio.to_thread(lambda: 'answered'), 3)finally:@@ -52,7 +65,7 @@ def test_a_frame_arriving_after_a_cancelled_read_is_not_lost():try:# A read cancelled while the child is silent (turn cancellation, Stop race).first = asyncio.create_task(worker.next_frame(None, ack=30))- await asyncio.sleep(.3)+ await async_wait_until(lambda: _parked(worker), timeout=10, what='the reader parked on the silent pipe')first.cancel()await asyncio.gather(first, return_exceptions=True)worker.send({'type': 'go'})diff --git a/tests/gateway/test_managed_worker_stop_before_hello.py b/tests/gateway/test_managed_worker_stop_before_hello.pyindex 9acb0214a16..30e80738b3a 100644--- a/tests/gateway/test_managed_worker_stop_before_hello.py+++ b/tests/gateway/test_managed_worker_stop_before_hello.py@@ -9,6 +9,7 @@ import psutilimport pytestfrom gateway.session_contract import Principal, SessionRef+from tests.waiting import async_wait_until@pytest.mark.platforms("linux")@@ -34,9 +35,8 @@ def test_stop_before_hello_terminates_child_and_settles_interrupted(monkeypatch)async def scenario():turn = asyncio.create_task(managed.execute_managed(authority, ref, row, policy=None))- async with asyncio.timeout(10):- while ref.session_id not in getattr(authority, '_managed_workers', {}):- await asyncio.sleep(.01)+ await async_wait_until(lambda: ref.session_id in getattr(authority, '_managed_workers', {}),+ timeout=10, what='the managed worker to be registered')assert managed.interrupt_managed(authority, actor, ref, 3) is Trueasync with asyncio.timeout(10):return await turndiff --git a/tests/gateway/test_responses_idem_replay_record.py b/tests/gateway/test_responses_idem_replay_record.pyindex 93c603fe636..93f94d04b6d 100644--- a/tests/gateway/test_responses_idem_replay_record.py+++ b/tests/gateway/test_responses_idem_replay_record.py@@ -6,6 +6,8 @@ import pytestfrom aiohttp import webfrom aiohttp.test_utils import TestClient, TestServer+from tests.waiting import async_wait_until+def _frames(text):return [json.loads(line[6:]) for line in text.splitlines() if line.startswith('data: ')]@@ -44,11 +46,11 @@ async def test_in_flight_retry_does_not_win_the_replay_record_without_deltas(apibody, headers = {'input': 'work', 'stream': True}, {'Idempotency-Key': 'lagging-publisher'}async with TestClient(TestServer(app)) as client:original = asyncio.create_task(client.post('/v1/responses', json=body, headers=headers))- async with asyncio.timeout(10):- while not calls:- await asyncio.sleep(.01)+ await async_wait_until(lambda: calls, timeout=10, what='the original turn to start')retry = asyncio.create_task(client.post('/v1/responses', json=body, headers=headers))- await asyncio.sleep(.2) # the retry joins the in-flight admission as an observer+ # The retry joins the in-flight admission as a second observer beside the original.+ await async_wait_until(lambda: any(len(o) >= 2 for o in getattr(owner, 'api_observers', {}).values()),+ timeout=10, what='the retry to join the in-flight admission as an observer')release.set()first, joined = await original, await retryassert first.status == joined.status == 200diff --git a/tests/gateway/test_runtime_bootstrap.py b/tests/gateway/test_runtime_bootstrap.pyindex 13274902838..bac7fa412c5 100644--- a/tests/gateway/test_runtime_bootstrap.py+++ b/tests/gateway/test_runtime_bootstrap.py@@ -103,10 +103,13 @@ async def test_old_socket_cleanup_cannot_unlink_replacement(tmp_path):def test_native_pipe_authenticated_peer_and_deadline(tmp_path):import timefrom gateway.runtime_bootstrap_windows import NativeControlServer, query_runtime_control+ import threading+ stalled = threading.Event() # the stalled handler hangs until teardown releases it+def handler(raw, subject):assert subject.startswith('sid:S-1-')if raw == b'stall':- time.sleep(1)+ stalled.wait(10)return json.dumps({'subject': subject}).encode() + b'\n'server = NativeControlServer(tmp_path, handler)server.start()@@ -121,6 +124,7 @@ def test_native_pipe_authenticated_peer_and_deadline(tmp_path):query_runtime_control(tmp_path, b'stall', 0.1)assert time.monotonic() - started < 2finally:+ stalled.set()server.close()assert not server._thread.is_alive()@@ -141,7 +145,7 @@ def test_native_pipe_handler_may_dial_its_own_pipe(tmp_path):except Exception as exc: # report, never kill the serving threadinner = {'error': repr(exc)}return json.dumps({'outer': inner}).encode() + b'\n'- time.sleep(2.5) # longer than the per-peer I/O budget+ time.sleep(2.5) # health: allow HX013 -- the handler must outlast the 2 s per-peer I/O budget under testreturn json.dumps({'inner': raw.decode()}).encode() + b'\n'server = NativeControlServer(tmp_path, handler)@@ -160,9 +164,42 @@ def test_native_pipe_never_drops_a_client_that_lands_between_idle_accepts(tmp_pawith DisconnectNamedPipe there dropped that client mid-request (WinError 233). The client isinjected at the server's first DisconnectNamedPipe, the widest point of that window."""import threading- import timeimport gateway.runtime_bootstrap_windows as rbwreal_disconnect, injected, armed = rbw._disconnect_pipe, {}, threading.Event()+ real_native, real_accept = rbw._native, rbw._accept+ landed, idle = threading.Event(), threading.Event()++ class _InjectedClient:+ """The injected client's ``_winapi``: reports when it reached the pipe."""+ def __init__(self, win):+ self._win = win++ def __getattr__(self, name):+ return getattr(self._win, name)++ def CreateFile(self, *args):+ try:+ handle = self._win.CreateFile(*args)+ except OSError as exc:+ if exc.winerror != 231: # 231 (all instances busy) queues on WaitNamedPipe next+ landed.set()+ raise+ landed.set() # it opened the idle instance+ return handle++ def WaitNamedPipe(self, *args):+ landed.set()+ return self._win.WaitNamedPipe(*args)++ def native():+ win = real_native()+ return _InjectedClient(win) if threading.current_thread() is injected.get("thread") else win++ def accept(handle, budget):+ connected = real_accept(handle, budget)+ if not connected:+ idle.set()+ return connecteddef query():try:@@ -175,13 +212,16 @@ def test_native_pipe_never_drops_a_client_that_lands_between_idle_accepts(tmp_painjected["thread"] = threading.Thread(target=query)injected["thread"].start()armed.set()- time.sleep(0.3) # let the client open (idle window) or queue on WaitNamedPipe (served)+ # let the client open (idle window) or queue on WaitNamedPipe (served)+ assert landed.wait(5), "the injected client never reached the pipe"real_disconnect(handle)monkeypatch.setattr(rbw, "_disconnect_pipe", disconnect_with_client_in_flight)+ monkeypatch.setattr(rbw, "_native", native)+ monkeypatch.setattr(rbw, "_accept", accept)server = rbw.NativeControlServer(tmp_path, lambda raw, subject: json.dumps({"echo": raw.decode()}).encode() + b"\n")server.start()try:- time.sleep(0.8) # at least one idle accept cycle+ assert idle.wait(10), "no idle accept cycle ran" # at least one idle accept cycleassert json.loads(rbw.query_runtime_control(tmp_path, b"hello", 5)) == {"echo": "hello"}assert armed.wait(5)injected["thread"].join(10)diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.pyindex e40517f0605..def7367584e 100644--- a/tests/gateway/test_session_authority_cancel_settlement.py+++ b/tests/gateway/test_session_authority_cancel_settlement.py@@ -293,13 +293,16 @@ async def test_settlement_failure_is_logged_and_does_not_kill_the_drain(tmp_path@pytest.mark.asyncio-async def test_storage_lock_during_claim_retries_in_place_and_keeps_waiters(tmp_path, monkeypatch):+async def test_storage_lock_during_claim_retries_in_place_and_keeps_waiters(tmp_path, monkeypatch, caplog):"""A writer held past the claim's patience (or a full disk) is transient. The drain must not diewith the committed head queued and its waiter parked forever: every _schedule caller isevent-driven, so nothing would re-arm it. It retries in place and runs the head once."""+ import loggingimport sqlite3from gateway import session_authority, session_finite+ from tests.waiting import async_wait_until+ caplog.set_level(logging.WARNING, logger='gateway.session_authority')db, authority = _authority(tmp_path, monkeypatch)monkeypatch.setattr(db, '_WRITE_PATIENCE_S', 0.2)monkeypatch.setattr(session_authority, '_CLAIM_RETRY_MIN_S', 0.05, raising=False)@@ -319,7 +322,9 @@ async def test_storage_lock_during_claim_retries_in_place_and_keeps_waiters(tmp_try:schedule(REF)task = authority.sessions['s'].task- await asyncio.sleep(0.6)+ # Two deferred claims: the drain hit the held writer and retried in place at least once.+ await async_wait_until(lambda: caplog.text.count('claim deferred by storage') >= 2 or task.done(),+ timeout=20, what='the drain to retry its claim behind the held writer')assert not task.done(), task.exception() if task.done() else Noneassert not waiter.done(), 'a transient storage error must not release accepted work'finally:diff --git a/tests/gateway/test_session_bot_retry.py b/tests/gateway/test_session_bot_retry.pyindex 82bd063524d..a36b08bd489 100644--- a/tests/gateway/test_session_bot_retry.py+++ b/tests/gateway/test_session_bot_retry.py@@ -63,6 +63,19 @@ def _admissions(bot):return list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False)+def _quiet(bot):+ """Nothing left that could admit another row: no receipt task, mailbox operation or drain runs."""+ authority = bot.authority+ return (not any(not task.done() for task in getattr(authority, '_bot_receipt_tasks', ()))+ and not getattr(authority, '_bot_mailbox_operations', None)+ and all(live.task is None or live.task.done() for live in authority.sessions.values()))+++async def _settle_quietly(bot):+ from tests.waiting import async_wait_until+ await async_wait_until(lambda: _quiet(bot), timeout=10, what='receipt tasks and drains to go idle')++async def _settled(bot, count):from gateway.session_bot import _resultfrom tools.bot_live_delivery import read_delivery_result@@ -89,7 +102,7 @@ async def test_transient_failure_retries_exactly_once_and_the_receipt_follows_thagain = await deliver(bot.connection, params)assert again['status'] == 'settled' and again['reply'] == 'pong'await recover_bot_deliveries(bot.authority)- await asyncio.sleep(0.05)+ await _settle_quietly(bot)assert len(_admissions(bot)) == 2@@ -105,7 +118,7 @@ async def test_retry_that_fails_again_and_non_transient_failures_are_never_replaassert receipt['reason'] == 'provider_server_error' and '503' in receipt['error'], receiptawait deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))await recover_bot_deliveries(bot.authority)- await asyncio.sleep(0.1)+ await _settle_quietly(bot)assert len(_admissions(bot)) == 2# Auth failures do not classify transient: settled failed, never retried.other = 'd' * 32@@ -116,7 +129,7 @@ async def test_retry_that_fails_again_and_non_transient_failures_are_never_replaif all(r['status'] == 'terminal' for r in _admissions(bot)) and len(_admissions(bot)) == 3:breakawait recover_bot_deliveries(bot.authority)- await asyncio.sleep(0.1)+ await _settle_quietly(bot)assert [r['request_id'] for r in _admissions(bot)][2:] == ['bot:' + other]from gateway.session_bot import _resultfrom tools.bot_live_delivery import read_delivery_result@@ -155,10 +168,18 @@ async def test_peer_dm_waiter_follows_the_retry_admission_to_its_answer(bot):"""``hermes peer dm`` waits on the delivery, not on the original admission id: once thatfails transiently its future never fires again, and the answer is the retry's."""from gateway.platforms.api_server_bot_chat import await_peer_receipt+ from gateway import session_botfrom gateway.session_bot import deliver+ from tests.waiting import async_wait_untilgate = asyncio.Event()import gateway.session_finite as finiteexecute = finite.execute_finite_admission+ wait_admission, followed = session_bot.peer_wait_admission, []++ def peer_wait_admission(authority, record):+ live = wait_admission(authority, record)+ followed.append(live)+ return liveasync def held(authority, ref, row):if row['request_id'].endswith(':retry'):@@ -166,6 +187,7 @@ async def test_peer_dm_waiter_follows_the_retry_admission_to_its_answer(bot):return await execute(authority, ref, row)finite.execute_finite_admission = held+ session_bot.peer_wait_admission = peer_wait_admissiontry:bot.errors[:] = ['Error code: 429 - rate limit exceeded']first = await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))@@ -174,12 +196,16 @@ async def test_peer_dm_waiter_follows_the_retry_admission_to_its_answer(bot):await asyncio.sleep(0.02)if len(_admissions(bot)) == 2:break- await asyncio.sleep(0.1)+ retry_id = _admissions(bot)[1]['admission_id']+ # The waiter re-read the delivery after the original failed and now follows the held retry.+ await async_wait_until(lambda: (retry_id, False) in followed or waiting.done(), timeout=10,+ what='the peer waiter to follow the retry admission')assert not waiting.done(), waiting.result()gate.set()receipt = await asyncio.wait_for(waiting, 5)finally:finite.execute_finite_admission = execute+ session_bot.peer_wait_admission = wait_admissionassert (receipt['status'], receipt['reply']) == ('settled', 'pong'), receiptassert receipt['retry_admission_id']@@ -212,7 +238,7 @@ async def test_receipt_file_stays_pending_while_a_draining_owner_leaves_the_retrawait asyncio.sleep(0.02)if _admissions(bot)[0]['status'] == 'terminal':break- await asyncio.sleep(0.1)+ await _settle_quietly(bot) # the original's receipt task has published its interim stateinterim = await await_delivery_async(bot.home, KEY, 0.2)assert interim['status'] == 'claimed' and len(_admissions(bot)) == 1, interimwaiting = asyncio.create_task(await_delivery_async(bot.home, KEY, 10))@@ -230,6 +256,7 @@ async def test_mailbox_file_lock_held_elsewhere_never_stalls_the_owner_loop(bot)"""The cross-process mailbox lock guards one receipt write, taken off the event loop: a DMrunner (another process) holding it delays only that write, never every other session, socketand delivery on the owner's loop, and never across an admission await."""+ import sysimport threadingimport timefrom gateway.session_bot import deliver@@ -237,18 +264,31 @@ async def test_mailbox_file_lock_held_elsewhere_never_stalls_the_owner_loop(bot)from tools.bot_live_delivery import _locked, _rootwith _locked(bot.home):pass+ from tests.waiting import async_wait_untilheld, release = threading.Event(), threading.Event()def foreign_holder():with _FileLock(_root(bot.home) / '.lock'):held.set()- release.wait(1.0)- threading.Thread(target=foreign_holder, daemon=True).start()+ release.wait(10) # the test releases it as soon as the loop has been measured+ holder = threading.Thread(target=foreign_holder, daemon=True)+ holder.start()assert held.wait(5)++ def queued_behind_holder():+ # Another thread (the off-loop receipt write) is parked in flock behind the holder.+ for ident, frame in sys._current_frames().items():+ if ident in (holder.ident, threading.get_ident()):+ continue+ while frame is not None:+ if frame.f_code.co_name == '_flock':+ return True+ frame = frame.f_back+ return Falsedelivering = asyncio.create_task(deliver(bot.connection, dict(id=KEY, profile='default', message='ping')))started = time.monotonic()- for _ in range(5):- await asyncio.sleep(0.02)+ # The loop keeps polling while the write waits off it; a write on the loop would block every poll.+ await async_wait_until(queued_behind_holder, timeout=10, what='the mailbox write to wait off the loop')loop_stall = time.monotonic() - startedrelease.set()receipt = await asyncio.wait_for(delivering, 5)diff --git a/tests/gateway/test_settlement_off_loop.py b/tests/gateway/test_settlement_off_loop.pyindex b54c2b4b9e3..bad176c266b 100644--- a/tests/gateway/test_settlement_off_loop.py+++ b/tests/gateway/test_settlement_off_loop.py@@ -7,6 +7,7 @@ import pytestfrom gateway.session_contract import Submissionfrom hermes_state_runtime import get_session_admissionfrom tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF+from tests.waiting import async_wait_until@pytest.mark.asyncio@@ -14,7 +15,7 @@ async def test_settlement_write_leaves_the_loop_free_and_publishes_in_order(tmp_from gateway import session_resultsdb, authority = _authority(tmp_path, monkeypatch)monkeypatch.setattr(authority, '_schedule', lambda ref: None)- loop_ran, events, served_during_write = threading.Event(), [], []+ loop_ran, writing, events, served_during_write = threading.Event(), threading.Event(), [], []authority.sessions['s'].event_stream.observers.add(lambda frame: events.append((frame['params']['type'], frame['params']['payload'].get('running'))))@@ -26,12 +27,14 @@ async def test_settlement_write_leaves_the_loop_free_and_publishes_in_order(tmp_def slow_settle(*args, **kwargs):# A contended writer: the owner loop must keep serving other work meanwhile.+ writing.set()served_during_write.append(loop_ran.wait(2))return settle(*args, **kwargs)monkeypatch.setattr(session_results, 'settle_session_input', slow_settle)async def other_session_work():- await asyncio.sleep(0.01)+ # Runs on the owner loop only once the settlement write is in flight off it.+ await async_wait_until(writing.is_set, timeout=10, what='the settlement write to start')loop_ran.set()with db:diff --git a/tests/hermes_cli/test_gateway_queued_unknown.py b/tests/hermes_cli/test_gateway_queued_unknown.pyindex 16e59b3a999..d2ffd2ceecb 100644--- a/tests/hermes_cli/test_gateway_queued_unknown.py+++ b/tests/hermes_cli/test_gateway_queued_unknown.py@@ -5,6 +5,7 @@ import jsonimport pytestfrom hermes_cli.gateway_chat_view import GatewayChatView+from tests.waiting import async_wait_until@pytest.mark.asyncio@@ -84,11 +85,14 @@ async def test_own_lost_turn_exits_from_its_unknown_completion_not_queued_detachreturn {'result': {}}async def lose_worker():- await asyncio.sleep(0.01)+ # Worker loss follows the receipt: the view already owns its admission.+ await async_wait_until(lambda: view.finite_admission == 'ours', timeout=5, what='the receipt')self.events.put_nowait({'method': 'event', 'params': {'session_id': 's', 'type': 'session.info','admission_id': 'ours', 'payload': {'pending': [{'admission_id': 'ours', 'status': 'unknown'}]}}})if yield_between:- await asyncio.sleep(0.01)+ # A separate WebSocket frame: the view renders session.info before the completion.+ await async_wait_until(lambda: any(r.get('admission_id') == 'ours' for r in view.pending),+ timeout=5, what='session.info rendered')self.events.put_nowait({'method': 'event', 'params': {'session_id': 's', 'type': 'message.complete','admission_id': 'ours', 'payload': {'outcome': 'unknown', 'text': 'Worker execution is unknown.'}}})asyncio.get_running_loop().create_task(lose_worker())