Skip to content

The agent that grows with you

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

Tekniumb8f1548c08e2
diff --git a/tests/acp_adapter/test_gateway_editor_mcp.py b/tests/acp_adapter/test_gateway_editor_mcp.py
index 34fa1091f6b..d7fbf9b1720 100644
--- a/tests/acp_adapter/test_gateway_editor_mcp.py
+++ b/tests/acp_adapter/test_gateway_editor_mcp.py
@@ -14,6 +14,7 @@ import pytest
from tests.acp_adapter.test_gateway_sessions import editor, viewer
from tests.gateway.test_normal_runtime_boot import control
+from tests.waiting import async_wait_until
class MCPModelPeer(BaseHTTPRequestHandler):
@@ -103,9 +104,8 @@ async def test_native_opposing_editor_mcp_survives_viewer_exit(daemon, specs, tm
bs = bc['result']['sessionId']
pending = asyncio.create_task(prompt(b, bs))
try:
- async with asyncio.timeout(25):
- while not (tmp_path / 'B.entered').exists():
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: (tmp_path / 'B.entered').exists(), timeout=25,
+ what="B's MCP tool call entered")
async with editor(daemon, tmp_path) as a:
await initialize(a)
ac = await a.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])
diff --git a/tests/acp_adapter/test_gateway_submit_retry.py b/tests/acp_adapter/test_gateway_submit_retry.py
index 7b56466283a..59c4a4444c9 100644
--- a/tests/acp_adapter/test_gateway_submit_retry.py
+++ b/tests/acp_adapter/test_gateway_submit_retry.py
@@ -12,6 +12,7 @@ from gateway.session_authority import LiveSession, initialize_session_authority
from gateway.session_controls import AuthorityConnection
from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
from hermes_state_runtime import list_session_admissions
+from tests.waiting import async_wait_until
class Wire:
@@ -72,9 +73,8 @@ async def test_retry_after_lost_submit_ack_is_one_admission(tmp_path, monkeypatc
await agent.prompt([acp.text_block('same words')], 's')
authority._schedule = schedule
if settled_before_retry:
- async with asyncio.timeout(5):
- while 'ACK_same words' not in agent._conn.updates:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: 'ACK_same words' in agent._conn.updates, timeout=5,
+ what='the lost turn settled before the retry')
response = await asyncio.wait_for(agent.prompt([acp.text_block('same words')], 's'), 5)
assert response.stop_reason == 'end_turn'
rows = list_session_admissions(authority.db, session_id='s', pending_only=False)
diff --git a/tests/gateway/fixtures/authority_controls_peer.py b/tests/gateway/fixtures/authority_controls_peer.py
index 9b603ba33ed..0fa0eeaa0c3 100644
--- a/tests/gateway/fixtures/authority_controls_peer.py
+++ b/tests/gateway/fixtures/authority_controls_peer.py
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import threading
+import time
import traceback
@@ -114,12 +115,14 @@ async def probe(peer, target):
assert list_gateway_approvals(route), 'real worker never blocked for approval'
assert target.exists(), 'effect preceded human consent'
# Rendering completes before the callback registers its shared projection.
- async with asyncio.timeout(3):
- while True:
- snapshot = await rpc(b, 3, 'session.resume')
- if snapshot['result'].get('prompts'):
- break
- await asyncio.sleep(.02)
+ deadline = time.monotonic() + 3
+ while True:
+ snapshot = await rpc(b, 3, 'session.resume')
+ if snapshot['result'].get('prompts'):
+ break
+ if time.monotonic() >= deadline:
+ raise TimeoutError
+ await asyncio.sleep(.02)
except TimeoutError:
raise AssertionError('approval-blocked worker absent from shared attach snapshot') from None
else:
diff --git a/tests/gateway/fixtures/hosted_auth_probe.py b/tests/gateway/fixtures/hosted_auth_probe.py
index 18229e4bc8c..788d40fbd84 100644
--- a/tests/gateway/fixtures/hosted_auth_probe.py
+++ b/tests/gateway/fixtures/hosted_auth_probe.py
@@ -17,6 +17,7 @@ from cryptography.hazmat.primitives.asymmetric import rsa
from websockets.asyncio.client import connect
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc
+from tests.waiting import async_wait_until
class OIDC(BaseHTTPRequestHandler):
@@ -214,26 +215,28 @@ def probe(tmp_path):
assert sibling['result']['driver_status']['counts'].get('running') == 1, sibling
model.release.set()
for actor, ws, _ in actors:
- async with asyncio.timeout(90):
- while True:
- state = await rpc(ws, 'groups.state', room_id=actor + '-room')
- counts = state['result']['driver_status']['counts']
- if not counts.get('running') and not counts.get('stopping'):
- assert counts.get('cancelled', 0) >= 1, state
- break
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 90
+ while True:
+ state = await rpc(ws, 'groups.state', room_id=actor + '-room')
+ counts = state['result']['driver_status']['counts']
+ if not counts.get('running') and not counts.get('stopping'):
+ assert counts.get('cancelled', 0) >= 1, state
+ break
+ assert time.monotonic() < deadline, f'{actor} room never settled its stop: {state}'
+ await asyncio.sleep(.1)
assert len(model.requests) == 2, model.requests
sent = await rpc(alice, 'groups.send', room_id='alice-room', event_id='approval',
payload={'text': '@two APPROVE_HOSTED', 'thread_id': 'approval-thread'})
assert sent['result']['accepted'], sent
- async with asyncio.timeout(90):
- while True:
- state = await rpc(alice, 'groups.state', room_id='alice-room')
- actions = state['result']['driver_status']['pending_actions']
- approvals = [a for a in actions if a['kind'] == 'approval']
- if approvals:
- break
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 90
+ while True:
+ state = await rpc(alice, 'groups.state', room_id='alice-room')
+ actions = state['result']['driver_status']['pending_actions']
+ approvals = [a for a in actions if a['kind'] == 'approval']
+ if approvals:
+ break
+ assert time.monotonic() < deadline, f'no approval was ever parked: {state}'
+ await asyncio.sleep(.1)
assert removal.exists()
action = approvals[0]
params = {k: action[k] for k in ('member_id', 'task_id', 'execution_generation', 'request_id')}
@@ -241,9 +244,8 @@ def probe(tmp_path):
assert denied.get('error', {}).get('message') == 'permission_denied', denied
accepted = await rpc(alice, 'groups.approve', room_id='alice-room', choice='once', **params)
assert accepted.get('result', {}).get('approved'), accepted
- async with asyncio.timeout(90):
- while removal.exists():
- await asyncio.sleep(.1)
+ await async_wait_until(lambda: not removal.exists(), timeout=90,
+ what='the approved removal to run')
assert 'FORBIDDEN' not in json.dumps(model.requests)
return {'actors': oidc.logins, 'rooms': ['alice-room', 'bob-room'],
diff --git a/tests/gateway/fixtures/local_session_peer.py b/tests/gateway/fixtures/local_session_peer.py
index ea366d2790e..47d68774fd2 100644
--- a/tests/gateway/fixtures/local_session_peer.py
+++ b/tests/gateway/fixtures/local_session_peer.py
@@ -7,6 +7,7 @@ from pathlib import Path
import shlex
import sys
import threading
+import time
import traceback
from authority_controls_peer import ModelPeer
@@ -101,12 +102,13 @@ async def probe(peer, target, kind):
assert resumed['result']['session_id'] == sid, resumed
submitted = await rpc(a, 'prompt.submit', session_id=sid, input_id='first', text='Remove owned fixture')
assert submitted.get('result', {}).get('status') == 'queued', submitted
- async with asyncio.timeout(25):
- while True:
- snapshot = await rpc(b, 'session.resume', session_id=sid)
- if snapshot['result'].get('prompts'):
- break
- await asyncio.sleep(.03)
+ deadline = time.monotonic() + 25
+ while True:
+ snapshot = await rpc(b, 'session.resume', session_id=sid)
+ if snapshot['result'].get('prompts'):
+ break
+ assert time.monotonic() < deadline, f'no prompt reached the shared attach: {snapshot}'
+ await asyncio.sleep(.03)
assert target.exists(), 'effect preceded consent'
ref = SessionRef(authority.profile_id, sid)
agent = authority.agent(ref)
diff --git a/tests/gateway/fixtures/shared_authority_peer.py b/tests/gateway/fixtures/shared_authority_peer.py
index 3b35fa5fcd9..c0b3c2bc1a4 100644
--- a/tests/gateway/fixtures/shared_authority_peer.py
+++ b/tests/gateway/fixtures/shared_authority_peer.py
@@ -62,6 +62,7 @@ async def probe():
from tui_gateway import server
from run_agent import AIAgent
from shared_authority_recovery import prepare_crash, recover_probe, verify_envelope_guards
+ from tests.waiting import async_wait_until
class CaptureAdapter(BasePlatformAdapter):
def __init__(self):
@@ -103,9 +104,7 @@ async def probe():
return
event = MessageEvent(text="MESSAGING_WARM", source=source, message_id="warm-1")
await adapter.handle_message(event)
- async with asyncio.timeout(35):
- while adapter._active_sessions:
- await asyncio.sleep(0.05)
+ await async_wait_until(lambda: not adapter._active_sessions, timeout=35, what='the warm-up turn to finish')
assert event._gateway_accepted, adapter.sent
assert any("LOCAL_ACK_MESSAGING_WARM" in text for text in adapter.sent), adapter.sent
entry = runner.session_store.get_or_create_session(source)
@@ -128,11 +127,9 @@ async def probe():
port = listener.getsockname()[1]
http = uvicorn.Server(uvicorn.Config(app, log_level="warning", lifespan="off", ws="websockets"))
task = asyncio.create_task(http.serve(sockets=[listener]))
- async with asyncio.timeout(10):
- while not http.started:
- if task.done():
- await task
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: http.started or task.done(), timeout=10, what='uvicorn to start')
+ if task.done():
+ await task
frames = []
receipt = {"messaging_completed": True, "stored_id": entry.session_id,
"unauthenticated_rejected": False, "ws_completed": False, "same_agent": False}
@@ -185,10 +182,9 @@ async def probe():
queued_event = MessageEvent(text='FIFO_SECOND', source=source, message_id='fifo-2')
queued_task = asyncio.create_task(adapter.handle_message(queued_event))
try:
- async with asyncio.timeout(3):
- while not any(r['request_id'] == 'fifo-2' for r in list_session_admissions(
- runner.session_authority.db, session_id=entry.session_id)):
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: any(r['request_id'] == 'fifo-2' for r in list_session_admissions(
+ runner.session_authority.db, session_id=entry.session_id)), timeout=3,
+ what='the queued FIFO_SECOND admission')
assert not adapter._pending_messages, 'second frontend queue owns accepted work'
receipt['durable_native_fifo'] = True
pending = list_session_admissions(runner.session_authority.db, session_id=entry.session_id)
@@ -212,9 +208,8 @@ async def probe():
finally:
peer.release.set()
await queued_task
- async with asyncio.timeout(10):
- while adapter._active_sessions:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: not adapter._active_sessions, timeout=10,
+ what='the FIFO turns to finish')
task_owner = runner.session_authority.sessions[entry.session_id].task
if task_owner is not None:
await task_owner
diff --git a/tests/gateway/test_api_authority_daemon.py b/tests/gateway/test_api_authority_daemon.py
index 5c1ea30e4b7..c42f839fa33 100644
--- a/tests/gateway/test_api_authority_daemon.py
+++ b/tests/gateway/test_api_authority_daemon.py
@@ -12,6 +12,7 @@ import aiohttp
from tests.gateway.fixtures.local_recovery_probe import daemon, websocket, rpc
from tests.gateway.fixtures.api_usage_peer import UsageModelPeer
+from tests.waiting import async_wait_until
def test_ordinary_daemon_api_ws_fifo_retry(tmp_path):
@@ -62,9 +63,8 @@ def test_ordinary_daemon_api_ws_fifo_retry(tmp_path):
assert response.status == 200, text
return text
pending = asyncio.create_task(follow())
- async with asyncio.timeout(10):
- while not any(row['request_id'].endswith(':daemon-retry') and row['status'] == 'queued' for row in rows()):
- await asyncio.sleep(.02)
+ await async_wait_until(lambda: any(row['request_id'].endswith(':daemon-retry') and row['status'] == 'queued'
+ for row in rows()), timeout=10, what='the follow-up queued')
peer.release.set()
completed = json.loads(await pending)
assert completed['usage'] == {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}, completed
diff --git a/tests/gateway/test_api_unknown_resolution.py b/tests/gateway/test_api_unknown_resolution.py
index 7742a664857..7b1360c7f18 100644
--- a/tests/gateway/test_api_unknown_resolution.py
+++ b/tests/gateway/test_api_unknown_resolution.py
@@ -233,7 +233,11 @@ async def test_http_resolve_unknown_refuses_stale_or_foreign_admission(
assert response.status == 409
assert (await response.json())["error"]["code"] == code
- await asyncio.sleep(0.05)
+ # A refused resolution must not release the FIFO: let any drain it scheduled run to the end
+ # (the restored drain parks on the unknown head) before reading what it left behind.
+ drain = owner.sessions["api-session"].task
+ if drain is not None:
+ await asyncio.wait_for(drain, 10)
rows = {
row["admission_id"]: row["status"]
for row in list_session_admissions(owner.db, session_id="api-session")
diff --git a/tests/hermes_cli/test_update_restore_authority.py b/tests/hermes_cli/test_update_restore_authority.py
index a2972b5b740..cd107321e30 100644
--- a/tests/hermes_cli/test_update_restore_authority.py
+++ b/tests/hermes_cli/test_update_restore_authority.py
@@ -9,6 +9,7 @@ import sqlite3
import threading
from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket
+from tests.waiting import async_wait_until
def test_restore_refuses_live_authority_without_changing_data(tmp_path):
@@ -44,9 +45,8 @@ def test_restore_refuses_live_authority_without_changing_data(tmp_path):
created = await rpc(ws, 'session.create', request_id='create', source='tui', cwd=str(home), toolsets=[])
session = created['result']['session_id']
await rpc(ws, 'prompt.submit', session_id=session, input_id='warm', text='WARM')
- async with asyncio.timeout(30):
- while dict(rows()).get('warm') != 'terminal':
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: dict(rows()).get('warm') == 'terminal', timeout=30, interval=.05,
+ what='the warm turn to settle')
snapshot = create_quick_snapshot(hermes_home=home)
assert snapshot, snapshot
await rpc(ws, 'prompt.submit', session_id=session, input_id='started', text='BLOCK_STARTED')