Skip to content

The agent that grows with you

test(hx013): wait for conditions, not the clock, in gateway and cli tests

Teknium7ad744f9d131
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 6a7b6d4a430..9a243ad2243 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -31,6 +31,7 @@ from gateway.platforms.api_server import (
)
from tools import approval as approval_mod
from tools import approval_gateway_wait
+from tests.waiting import async_wait_until
# ---------------------------------------------------------------------------
@@ -718,7 +719,10 @@ class TestRunEvents:
# The server only notices the dropped socket on its next write.
_mark_run_event(adapter, run_id, "run.steered", accepted=False)
assert "run.steered" in await frame(second)
- await asyncio.sleep(0.05)
+ stream = adapter._run_streams[run_id]
+ # ceiling past the 10s SSE keepalive, whose write also detaches a dead socket
+ await async_wait_until(lambda: len(stream.subscribers) == 1, timeout=30,
+ what="the dropped subscriber to detach")
_mark_run_event(adapter, run_id, "approval.responded", choice="once")
assert "approval.responded" in await frame(second)
diff --git a/tests/gateway/test_authority_unknown_resolution.py b/tests/gateway/test_authority_unknown_resolution.py
index 64dc8bb6922..ee111a0e424 100644
--- a/tests/gateway/test_authority_unknown_resolution.py
+++ b/tests/gateway/test_authority_unknown_resolution.py
@@ -11,6 +11,7 @@ from gateway.session_authority import LiveSession, initialize_session_authority
from gateway.session_contract import SessionRef, Submission
from gateway.session_controls import AuthorityConnection
from hermes_state_runtime import RuntimeStoreError, claim_session_input, list_session_admissions
+from tests.waiting import async_wait_until
class Peer:
@@ -64,8 +65,10 @@ async def test_resolve_unknown_releases_the_paused_follower_exactly_once(tmp_pat
try:
resumed = (await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}}))['result']
assert [r['status'] for r in resumed['pending']] == ['unknown', 'queued']
- # The follower stays paused behind the unknown head; nothing runs on its own.
- await asyncio.sleep(0.05)
+ # The follower stays paused behind the unknown head; nothing runs on its own. Only a drain
+ # runs a turn, so once no drain is live (none scheduled, or it paused) none can run later.
+ live = authority.sessions['s']
+ await async_wait_until(lambda: live.task is None or live.task.done(), what='no live drain')
assert executed == []
reply = await viewer.dispatch({'id': 2, 'method': 'prompt.resolve_unknown', 'params': {
'session_id': 's', 'admission_id': unknown['admission_id'],
@@ -112,7 +115,8 @@ async def test_resolve_unknown_is_fenced_by_generation_and_capability(tmp_path,
foreign = await owner.dispatch({'id': 4, 'method': 'prompt.resolve_unknown',
'params': {**params, 'session_id': 'other'}})
assert 'error' in foreign
- await asyncio.sleep(0.05)
+ live = authority.sessions['s']
+ await async_wait_until(lambda: live.task is None or live.task.done(), what='no live drain')
rows = {r['admission_id']: r['status'] for r in list_session_admissions(authority.db, session_id='s')}
assert rows[unknown['admission_id']] == 'unknown' and rows[follower.admission_id] == 'queued'
assert executed == []
diff --git a/tests/gateway/test_managed_runtime_live_drain.py b/tests/gateway/test_managed_runtime_live_drain.py
index 08832475699..a27a10bc0e7 100644
--- a/tests/gateway/test_managed_runtime_live_drain.py
+++ b/tests/gateway/test_managed_runtime_live_drain.py
@@ -9,6 +9,7 @@ import threading
from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
from tests.gateway.test_normal_runtime_boot import control
+import time
def test_managed_turn_finishes_inside_configured_restart_drain(tmp_path):
@@ -45,9 +46,10 @@ def test_managed_turn_finishes_inside_configured_restart_drain(tmp_path):
assert await asyncio.to_thread(peer.blocked.wait, 30)
accepted = await asyncio.to_thread(control, home, 'pause-for-update')
assert accepted['pausing'] is True, accepted
- async with asyncio.timeout(15):
- while (await asyncio.to_thread(control, home, 'identify'))['state'] != 'draining':
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 15
+ while (await asyncio.to_thread(control, home, 'identify'))['state'] != 'draining':
+ assert time.monotonic() < deadline, 'owner never reported draining'
+ await asyncio.sleep(.05)
peer.release.set()
await asyncio.to_thread(process.wait, 50)
try:
diff --git a/tests/gateway/test_managed_worker_detached_work.py b/tests/gateway/test_managed_worker_detached_work.py
index c31baac9812..6c6dc711f21 100644
--- a/tests/gateway/test_managed_worker_detached_work.py
+++ b/tests/gateway/test_managed_worker_detached_work.py
@@ -19,6 +19,7 @@ import threading
import pytest
from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+from tests.waiting import async_wait_until
def test_registered_worker_process_cannot_receive_async_completions(monkeypatch):
@@ -97,9 +98,9 @@ def test_managed_turn_runs_detachable_work_inline_and_leaves_no_orphan(tmp_path)
sid = session['result']['session_id']
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='run', text='run the job')
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='the run admission to settle')
return (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']
try:
with daemon(root, home, env, barrier=False) as (_owner, desc):
diff --git a/tests/gateway/test_managed_worker_trampoline.py b/tests/gateway/test_managed_worker_trampoline.py
index 4ca0465c98d..ea14d690512 100644
--- a/tests/gateway/test_managed_worker_trampoline.py
+++ b/tests/gateway/test_managed_worker_trampoline.py
@@ -21,6 +21,7 @@ import pytest
from hermes_state import SessionDB
from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
LAUNCHER = ('import subprocess, sys\n'
'child = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=sys.stdin)\n'
@@ -123,9 +124,9 @@ def test_managed_worker_completes_through_interpreter_trampoline(tmp_path):
sid = created['result']['session_id']
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='tramp-input', text='TRAMPOLINE_PROBE')
assert 'result' in submitted, submitted
- async with asyncio.timeout(90):
- while query('SELECT status FROM session_admissions WHERE request_id=?', ('tramp-input',)) in ([('queued',)], [('started',)]):
- await asyncio.sleep(.05)
+ await async_wait_until(
+ lambda: query('SELECT status FROM session_admissions WHERE request_id=?', ('tramp-input',))
+ not in ([('queued',)], [('started',)]), timeout=90, interval=.05, what='the trampoline admission to leave queued/started')
evidence = {'admissions': query('SELECT request_id,status FROM session_admissions'),
'workers': query('SELECT execution_id,status FROM worker_executions'),
'launches': launches.read_text(encoding='utf-8') if launches.exists() else None,
@@ -142,9 +143,7 @@ def test_managed_worker_completes_through_interpreter_trampoline(tmp_path):
def leftovers():
return [(p.pid, p.cmdline()) for p in psutil.Process(owner.pid).children(recursive=True)
if p.is_running() and p.status() != psutil.STATUS_ZOMBIE]
- async with asyncio.timeout(15):
- while leftovers():
- await asyncio.sleep(.1)
+ await async_wait_until(lambda: not leftovers(), timeout=15, interval=.1, what='the launcher chain to be reaped')
assert leftovers() == []
print(json.dumps({'owner_pid': owner.pid, 'launcher_pid': workers[0]['launcher'], 'worker_pid': workers[0]['child']}))
diff --git a/tests/gateway/test_messaging_stop_owner_turn.py b/tests/gateway/test_messaging_stop_owner_turn.py
index 2d2821b781a..fd68f7246da 100644
--- a/tests/gateway/test_messaging_stop_owner_turn.py
+++ b/tests/gateway/test_messaging_stop_owner_turn.py
@@ -9,6 +9,7 @@ drain over a real SessionDB; only agent construction/conversation is a stand-in.
import asyncio
import pytest
+from tests.waiting import async_wait_until
def _owner(monkeypatch):
@@ -31,9 +32,7 @@ def _owner(monkeypatch):
async def _until(predicate, timeout=10):
- async with asyncio.timeout(timeout):
- while not predicate():
- await asyncio.sleep(0.01)
+ await async_wait_until(predicate, timeout=timeout)
@pytest.mark.asyncio
diff --git a/tests/gateway/test_owner_loop_writes_class.py b/tests/gateway/test_owner_loop_writes_class.py
index f7fee79af62..a7b1a486dcd 100644
--- a/tests/gateway/test_owner_loop_writes_class.py
+++ b/tests/gateway/test_owner_loop_writes_class.py
@@ -9,6 +9,7 @@ import threading
from types import SimpleNamespace
import pytest
+from tests.waiting import async_wait_until
def _owner(tmp_path, monkeypatch, handle):
@@ -39,9 +40,8 @@ def _local(authority, owner, tmp_path, source='cli', request_id='m'):
async def _terminal(db, receipt):
import hermes_state_runtime as rt
- async with asyncio.timeout(10):
- while rt.get_session_admission(db, admission_id=receipt.admission_id)['status'] != 'terminal':
- await asyncio.sleep(0.02)
+ await async_wait_until(lambda: rt.get_session_admission(db, admission_id=receipt.admission_id)['status'] == 'terminal',
+ timeout=10, interval=0.02, what='the admission to settle')
async def _model_prepare(authority, owner, tmp_path, db):
diff --git a/tests/gateway/test_responses_output_order.py b/tests/gateway/test_responses_output_order.py
index 625708ab19b..767eee98803 100644
--- a/tests/gateway/test_responses_output_order.py
+++ b/tests/gateway/test_responses_output_order.py
@@ -5,6 +5,7 @@ import json
import pytest
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
+from tests.waiting import async_wait_until
@pytest.mark.asyncio
@@ -40,9 +41,8 @@ async def test_output_indices_survive_completion_order_and_eviction(api, owner):
pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))
await asyncio.wait_for(entered.wait(), 5)
pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))
- async with asyncio.timeout(5):
- while sum(map(len, owner.api_observers.values())) < 2:
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: sum(map(len, owner.api_observers.values())) >= 2, timeout=5,
+ what='both streams to observe the run')
release.set()
responses = await asyncio.gather(*pending)
terminal = []
@@ -95,13 +95,12 @@ async def test_late_stream_observer_receives_defined_output_indices(api, owner):
pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))
await asyncio.wait_for(entered.wait(), 5)
# Ensure the first stream actually published the tool items before the retry joins.
- async with asyncio.timeout(5):
- while api._current_response_store()._conn.execute('SELECT COUNT(*) FROM response_output_order').fetchone()[0] < 2:
- await asyncio.sleep(.01)
+ await async_wait_until(
+ lambda: api._current_response_store()._conn.execute('SELECT COUNT(*) FROM response_output_order').fetchone()[0] >= 2,
+ timeout=5, what='the first stream to publish its tool items')
pending.append(asyncio.create_task(client.post('/v1/responses', json=body, headers=headers)))
- async with asyncio.timeout(5):
- while sum(map(len, owner.api_observers.values())) < 2:
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: sum(map(len, owner.api_observers.values())) >= 2, timeout=5,
+ what='both streams to observe the run')
release.set()
responses = await asyncio.gather(*pending)
second = [json.loads(line[6:]) for line in (await responses[1].text()).splitlines()
diff --git a/tests/gateway/test_session_busy_controls.py b/tests/gateway/test_session_busy_controls.py
index 90a380643dc..7b1d4f3501a 100644
--- a/tests/gateway/test_session_busy_controls.py
+++ b/tests/gateway/test_session_busy_controls.py
@@ -11,6 +11,7 @@ import pytest
from websockets.asyncio.client import connect
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
class CorrectionModel(BaseHTTPRequestHandler):
@@ -90,9 +91,8 @@ def admissions(home):
async def settled(home):
- async with asyncio.timeout(40):
- while not admissions(home) or any(r[1] != 'terminal' for r in admissions(home)):
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: (rows := admissions(home)) and all(r[1] == 'terminal' for r in rows),
+ timeout=40, interval=.05, what='every admission to settle')
@pytest.mark.platforms("linux")
diff --git a/tests/gateway/test_session_commands.py b/tests/gateway/test_session_commands.py
index 99add7458b6..e10a1bc2a5e 100644
--- a/tests/gateway/test_session_commands.py
+++ b/tests/gateway/test_session_commands.py
@@ -14,6 +14,7 @@ from websockets.asyncio.client import connect
from websockets.exceptions import InvalidStatus
from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket
+from tests.waiting import async_wait_until
@pytest.mark.platforms("linux")
@@ -78,9 +79,8 @@ def test_ordinary_daemon_slash_skill_uses_durable_fifo(tmp_path):
assert 'SLASH_SKILL_BODY' not in result['result']['display'], result
assert not peer.requests and not rows(), 'resolution executed a turn'
await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_SLASH')
- async with asyncio.timeout(30):
- while not rows() or rows()[0][1] != 'terminal':
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: (r := rows()) and r[0][1] == 'terminal', timeout=30, interval=.05,
+ what='the warm turn to settle')
block = await rpc(ws, 'prompt.submit', session_id=sid, input_id='block', text='BLOCK_STARTED')
assert block.get('result', {}).get('status') == 'queued', block
assert await asyncio.to_thread(peer.blocked.wait, 25), ([m for r in peer.requests for m in r['messages'] if m['role'] == 'user'], rows())
@@ -111,9 +111,8 @@ def test_ordinary_daemon_slash_skill_uses_durable_fifo(tmp_path):
receipts.append(result)
assert 'mid-turn' in result.get('result', {}).get('output', ''), result
peer.release.set()
- async with asyncio.timeout(45):
- while any(row[1] != 'terminal' for row in rows()):
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: all(row[1] == 'terminal' for row in rows()), timeout=45, interval=.05,
+ what='every admission to settle')
title = await command(command='title Owned slash title')
assert 'Owned slash title' in title['result']['output'], title
listing = await rpc(ws, 'session.list')
diff --git a/tests/gateway/test_stream_consumer.py b/tests/gateway/test_stream_consumer.py
index cbad4684554..a5951046a77 100644
--- a/tests/gateway/test_stream_consumer.py
+++ b/tests/gateway/test_stream_consumer.py
@@ -600,7 +600,7 @@ class TestFinalResponseDeliveryGuard:
consumer = GatewayStreamConsumer(adapter, "chat_123", StreamConsumerConfig(edit_interval=0.01, buffer_threshold=5))
consumer.on_delta("x" * 1200) # past the 500-codepoint floor of the safe limit
task = asyncio.create_task(consumer.run())
- await asyncio.sleep(0.3)
+ await asyncio.sleep(0.3) # health: allow HX013 -- the window is the measurement: passes per 0.3s tell a yielding loop from a spinning one
passes = adapter.send.await_count
consumer.finish()
await task
diff --git a/tests/hermes_cli/test_safe_mode.py b/tests/hermes_cli/test_safe_mode.py
index 51c8f482039..8b7b23b9c0a 100644
--- a/tests/hermes_cli/test_safe_mode.py
+++ b/tests/hermes_cli/test_safe_mode.py
@@ -22,6 +22,7 @@ import time
import pytest
from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+from tests.waiting import async_wait_until
class Model(BaseHTTPRequestHandler):
@@ -175,9 +176,9 @@ def test_canonical_safe_launch_is_frozen_policy_executed_in_isolated_worker(tmp_
sid = created['result']['session_id']
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='ordinary-input', text='ORDINARY_PROBE')
assert 'result' in submitted, submitted
- async with asyncio.timeout(60):
- while query('SELECT status FROM session_admissions WHERE request_id=?', ('ordinary-input',)) != [('terminal',)]:
- await asyncio.sleep(.05)
+ await async_wait_until(
+ lambda: query('SELECT status FROM session_admissions WHERE request_id=?', ('ordinary-input',)) == [('terminal',)],
+ timeout=60, interval=.05, what='the ordinary turn to settle')
return sid
def safe_cli(request_tag, *flags):