Skip to content

The agent that grows with you

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

Tekniumd77b830ee23c
diff --git a/tests/acp_adapter/test_gateway_acp_session_end.py b/tests/acp_adapter/test_gateway_acp_session_end.py
index 21eeca64205..d78408fef8b 100644
--- a/tests/acp_adapter/test_gateway_acp_session_end.py
+++ b/tests/acp_adapter/test_gateway_acp_session_end.py
@@ -89,9 +89,10 @@ async def test_acp_session_left_mid_turn_ends_once_its_fifo_drains(tmp_path, mon
from gateway.session_local import create_local_session
from hermes_state_local import local_receipt
- release = asyncio.Event()
+ release, started = asyncio.Event(), asyncio.Event()
async def execute(authority, ref, row): # the model turn; drain + settlement stay real
+ started.set()
await release.wait()
return 'done'
@@ -111,8 +112,9 @@ async def test_acp_session_left_mid_turn_ends_once_its_fifo_drains(tmp_path, mon
target = local_receipt(authority.db, ref.session_id)['entry']['session_id']
reply = await viewer.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': ref.session_id}})
assert 'result' in reply, reply
+ started.clear()
await authority.submit(viewer.actor, Submission(source + '-turn', ref, {'text': 'work'}, 'queue'))
- await asyncio.sleep(0.1)
+ await asyncio.wait_for(started.wait(), 10) # the turn is running, not merely queued
await viewer.close()
assert authority.db.get_session(target)['ended_at'] is None, 'running work keeps the session open'
rows[source] = ref, target
diff --git a/tests/acp_adapter/test_gateway_editor_clarify.py b/tests/acp_adapter/test_gateway_editor_clarify.py
index bfae2f6656d..7422bfab93d 100644
--- a/tests/acp_adapter/test_gateway_editor_clarify.py
+++ b/tests/acp_adapter/test_gateway_editor_clarify.py
@@ -11,6 +11,7 @@ import json
import pytest
from tests.acp_adapter.test_gateway_sessions import editor, viewer
+import time
@pytest.mark.platforms("linux")
@@ -28,9 +29,10 @@ async def test_editor_answers_canonical_clarify_through_clarify_respond(
turn = None
if restored:
accepted = await ws.rpc("prompt.submit", session_id=sid, input_id="cli-turn", text="Ask my color")
- async with asyncio.timeout(30):
- while not (await ws.rpc("session.resume", session_id=sid))["prompts"]:
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 30
+ while not (await ws.rpc("session.resume", session_id=sid))["prompts"]:
+ assert time.monotonic() < deadline, "the CLI turn's clarify never reached the snapshot"
+ await asyncio.sleep(.05)
async with editor(daemon, tmp_path) as acp:
capabilities = {"elicitation": {"form": {}}} if form else {}
assert "result" in await acp.rpc("initialize", protocolVersion=1, clientCapabilities=capabilities)
@@ -39,10 +41,11 @@ async def test_editor_answers_canonical_clarify_through_clarify_respond(
turn = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,
prompt=[{"type": "text", "text": "Ask my color"}]))
method = "elicitation/create" if form else "session/request_permission"
- async with asyncio.timeout(30):
- while not any(f.get("method") == method for f in acp.frames):
- assert turn is None or not turn.done(), turn.result()
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 30
+ while not any(f.get("method") == method for f in acp.frames):
+ assert turn is None or not turn.done(), turn.result()
+ assert time.monotonic() < deadline, f"no {method} request reached the editor"
+ await asyncio.sleep(.05)
request = next(f for f in acp.frames if f.get("method") == method)
params = request["params"]
assert params["sessionId"] == sid
@@ -61,10 +64,11 @@ async def test_editor_answers_canonical_clarify_through_clarify_respond(
reply = await asyncio.wait_for(turn, 40)
assert reply.get("result", {}).get("stopReason") == "end_turn", reply
else:
- async with asyncio.timeout(40):
- while (await ws.rpc("prompt.receipt", session_id=sid,
- admission_id=accepted["admission_id"]))["status"] != "terminal":
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 40
+ while (await ws.rpc("prompt.receipt", session_id=sid,
+ admission_id=accepted["admission_id"]))["status"] != "terminal":
+ assert time.monotonic() < deadline, "the answered CLI turn never settled"
+ await asyncio.sleep(.05)
tool_results = [m for messages in model_peer.requests for m in messages if m["role"] == "tool"]
assert any("green" in json.dumps(m) for m in tool_results), tool_results
@@ -84,10 +88,11 @@ async def test_dismissed_clarify_card_releases_the_turn_with_skip(daemon, tmp_pa
assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])
turn = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,
prompt=[{"type": "text", "text": "Ask my color"}]))
- async with asyncio.timeout(30):
- while not any(f.get("method") == "session/request_permission" for f in acp.frames):
- assert not turn.done(), turn.result()
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 30
+ while not any(f.get("method") == "session/request_permission" for f in acp.frames):
+ assert not turn.done(), turn.result()
+ assert time.monotonic() < deadline, "no session/request_permission reached the editor"
+ await asyncio.sleep(.05)
request = next(f for f in acp.frames if f.get("method") == "session/request_permission")
acp.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request["id"],
"result": {"outcome": {"outcome": "cancelled"}}}).encode() + b"\n")
diff --git a/tests/acp_adapter/test_gateway_queued_unknown.py b/tests/acp_adapter/test_gateway_queued_unknown.py
index 105498443e0..9414b2c4ff4 100644
--- a/tests/acp_adapter/test_gateway_queued_unknown.py
+++ b/tests/acp_adapter/test_gateway_queued_unknown.py
@@ -7,6 +7,7 @@ import pytest
from acp_adapter.gateway_server import GatewayACPAgent
from hermes_cli.gateway_client import GatewayClientError
+from tests.waiting import async_wait_until
@pytest.mark.asyncio
@@ -88,7 +89,8 @@ async def test_editor_own_lost_turn_reports_unknown_not_end_turn(yield_between):
await agent._project({'session_id': 's', 'type': 'session.info',
'payload': {'pending': [{'admission_id': 'ours', 'status': 'unknown'}]}})
if yield_between:
- await asyncio.sleep(0.01)
+ # session.info alone must wake and settle the prompt before the completion arrives.
+ await async_wait_until(submitted.done, what='the prompt woke on session.info')
await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'ours',
'payload': {'outcome': 'unknown', 'text': 'Worker execution is unknown.'}})
diff --git a/tests/gateway/fixtures/authority_clarify_peer.py b/tests/gateway/fixtures/authority_clarify_peer.py
index 71a796d9cac..1627c415b99 100644
--- a/tests/gateway/fixtures/authority_clarify_peer.py
+++ b/tests/gateway/fixtures/authority_clarify_peer.py
@@ -6,6 +6,7 @@ import os
from pathlib import Path
import threading
import traceback
+import time
class ModelPeer(BaseHTTPRequestHandler):
@@ -91,16 +92,15 @@ async def probe(peer):
await rpc(a, 1, 'session.resume')
await rpc(b, 1, 'session.resume')
assert 'result' in await rpc(a, 2, 'prompt.submit', input_id='clarify-first', text='Ask my color')
- try:
- async with asyncio.timeout(15):
- while True:
- snapshot = await rpc(b, 3, 'session.resume')
- prompts = snapshot['result']['prompts']
- if prompts:
- break
- await asyncio.sleep(.05)
- except TimeoutError:
- raise AssertionError('real clarify waiter missing from shared snapshot') from None
+ deadline = time.monotonic() + 15
+ while True:
+ snapshot = await rpc(b, 3, 'session.resume')
+ prompts = snapshot['result']['prompts']
+ if prompts:
+ break
+ if time.monotonic() >= deadline:
+ raise AssertionError('real clarify waiter missing from shared snapshot')
+ await asyncio.sleep(.05)
prompt = prompts[0]
assert prompt['kind'] == 'clarify', prompt
assert clarify_gateway.has_pending(authority.sessions[ref.session_id].route)
diff --git a/tests/gateway/fixtures/authority_stream_peer.py b/tests/gateway/fixtures/authority_stream_peer.py
index a625720946c..2b12eeb4169 100644
--- a/tests/gateway/fixtures/authority_stream_peer.py
+++ b/tests/gateway/fixtures/authority_stream_peer.py
@@ -10,6 +10,8 @@ import queue
import socket
import threading
import traceback
+from tests.waiting import async_wait_until
+import time
class ModelPeer(BaseHTTPRequestHandler):
@@ -171,7 +173,8 @@ async def probe(peer, target):
async def witness_blockage():
nonlocal blocked_bytes, kernel_queued
- while not b.complete.is_set():
+ deadline = time.monotonic() + 60 # b.complete ends the sampling; this bounds a hang
+ while not b.complete.is_set() and time.monotonic() < deadline:
buffered = server_transport.get_write_buffer_size()
if buffered > server_transport.get_write_buffer_limits()[1]:
blocked_bytes = max(blocked_bytes, buffered)
@@ -187,10 +190,9 @@ async def probe(peer, target):
# The idle session.info is published after message.complete (its terminal frame); wait for
# it on every observer that sees the whole stream before reading "the last event".
for observer in (b,) if peer.blocked else (a, b):
- async with asyncio.timeout(10):
- while not (observer.events and observer.events[-1]['type'] == 'session.info'
- and observer.events[-1].get('payload', {}).get('running') is False):
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: observer.events and observer.events[-1]['type'] == 'session.info'
+ and observer.events[-1].get('payload', {}).get('running') is False,
+ timeout=10, what='the idle session.info after message.complete')
assert target.read_text() == 'owned-effect'
agent = authority.agent(ref)
assert isinstance(agent, AIAgent)
@@ -210,9 +212,7 @@ async def probe(peer, target):
assert a.events == b.events, 'observers saw competing event ordering/stamps'
events = b.events
if peer.blocked:
- async with asyncio.timeout(5):
- while not a.events:
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: a.events, timeout=5, what='the resumed slow observer to read a frame')
assert a.events == events[:len(a.events)], 'slow observer prefix has competing stamps'
with fanout._lock:
assert len(fanout._peers) <= 2
diff --git a/tests/gateway/fixtures/legacy_migration_probe.py b/tests/gateway/fixtures/legacy_migration_probe.py
index a7a3e219947..eccebd665e7 100644
--- a/tests/gateway/fixtures/legacy_migration_probe.py
+++ b/tests/gateway/fixtures/legacy_migration_probe.py
@@ -9,6 +9,7 @@ import sys
import threading
from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
def probe(base, legacy_root, owner_root=None):
@@ -39,9 +40,8 @@ def probe(base, legacy_root, owner_root=None):
db.row_factory = sqlite3.Row
return [dict(r) for r in db.execute(sql, args)]
async def wait_settled():
- async with asyncio.timeout(45):
- while any(r['status'] != 'terminal' for r in query('SELECT status FROM session_admissions')):
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: all(r['status'] == 'terminal' for r in query('SELECT status FROM session_admissions')),
+ timeout=45, interval=.05, what='every admission to settle')
async def run(desc):
async with websocket(home, desc) as ws:
first = await rpc(ws, 'session.resume', session_id=sid)
diff --git a/tests/gateway/fixtures/native_ingress_trust_multiplex.py b/tests/gateway/fixtures/native_ingress_trust_multiplex.py
index 8c05d1f2690..c9f5392505d 100644
--- a/tests/gateway/fixtures/native_ingress_trust_multiplex.py
+++ b/tests/gateway/fixtures/native_ingress_trust_multiplex.py
@@ -2,6 +2,7 @@
import asyncio
from copy import deepcopy
import json
+from tests.waiting import async_wait_until
async def multiplex_probe(runner, authority, primary, state, mode, peer):
@@ -85,9 +86,7 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):
event = MessageEvent(text='MULTIPLEX_NATIVE', source=source, message_id='mux-1')
await adapter.handle_message(event)
- async with asyncio.timeout(15):
- while adapter._active_sessions:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: not adapter._active_sessions, timeout=15, what='the adapter to finish its session')
entry = runner.session_store.get_or_create_session(source)
committed = rows(entry.session_id)
assert committed and committed[0]['outcome'] == 'completed', (committed, adapter.deliveries)
@@ -100,9 +99,7 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):
denied = MessageEvent(text='WRONG_TRANSPORT_SENDER', message_id='deny', source=adapter.build_source(
chat_id='mux-chat', chat_type='dm', user_id='runtime-only'))
await adapter.handle_message(denied)
- 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 adapter to finish its session')
assert rows(entry.session_id) == committed
if mode == 'multiplex':
sessions_before = set(authority.sessions)
@@ -110,9 +107,7 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):
profile='transport', chat_id='unowned-runtime', bot_profile='transport'))
unowned = adapter.build_source(chat_id='unowned-runtime', chat_type='dm', user_id='fixture-user')
await adapter.handle_message(MessageEvent(text='NO_SECONDARY_DB_OWNER', source=unowned, message_id='unowned'))
- 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 adapter to finish its session')
assert set(authority.sessions) == sessions_before, 'launch DB impersonated secondary runtime'
runner.config.profile_routes = [route]
await adapter.handle_message(MessageEvent(text='BLOCK_FIFO', source=source, message_id='busy-1'))
@@ -123,17 +118,14 @@ async def multiplex_probe(runner, authority, primary, state, mode, peer):
# A durable FIFO row, not an adapter-local queue: the bound is wall-clock only (the
# admission commits on the owner's writer, which a loaded runner can delay), like the
# model-gate and drain waits above.
- async with asyncio.timeout(10):
- while not any(row['request_id'] == 'busy-2' for row in rows(entry.session_id)):
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: any(row['request_id'] == 'busy-2' for row in rows(entry.session_id)),
+ timeout=10, what='the queued busy-2 FIFO row')
assert not adapter._pending_messages, 'callback wrapper restored adapter-local queue'
(state / '.env').write_text('TELEGRAM_ALLOWED_USERS=runtime-only\nOPENAI_API_KEY=runtime-fresh-key\n')
finally:
peer.release.set()
await 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 adapter to finish its session')
# The busy receive returned at commit; the queued turn finishes on the FIFO drain.
if authority.sessions[entry.session_id].task is not None:
await asyncio.wait_for(authority.sessions[entry.session_id].task, 10)
diff --git a/tests/gateway/fixtures/session_policy_peer.py b/tests/gateway/fixtures/session_policy_peer.py
index 3cd06458b13..ed88c236762 100644
--- a/tests/gateway/fixtures/session_policy_peer.py
+++ b/tests/gateway/fixtures/session_policy_peer.py
@@ -7,6 +7,7 @@ from pathlib import Path
import sys
import threading
import traceback
+from tests.waiting import async_wait_until
class Peer(BaseHTTPRequestHandler):
@@ -118,9 +119,8 @@ async def probe(peer):
accepted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=source, text='Write owned cwd proof')
assert 'result' in accepted, accepted
for sid in sessions:
- async with asyncio.timeout(30):
- while authority.sessions[sid].task is None:
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: authority.sessions[sid].task is not None, timeout=30,
+ what='the admitted turn to be scheduled')
await asyncio.wait_for(authority.sessions[sid].task, 40)
for source, sid, ws in zip(('cli', 'tui', 'gui'), sessions, sockets):
agent = authority.agent(SessionRef(authority.profile_id, sid))