Skip to content

The agent that grows with you

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

Teknium648e1e13e152
diff --git a/tests/acp_adapter/test_gateway_sessions.py b/tests/acp_adapter/test_gateway_sessions.py
index f9900e47e4e..9d966e5e839 100644
--- a/tests/acp_adapter/test_gateway_sessions.py
+++ b/tests/acp_adapter/test_gateway_sessions.py
@@ -3,12 +3,14 @@ import asyncio
from contextlib import asynccontextmanager
import json
import sys
+import time
import pytest
from websockets.asyncio.client import connect
from hermes_cli.gateway_client import GatewayClient
from tests.gateway.test_normal_runtime_boot import control
+from tests.waiting import async_wait_until
@asynccontextmanager
@@ -82,13 +84,14 @@ async def test_acp_transport_shares_canonical_history_and_order(daemon, tmp_path
assert reply.get("result", {}).get("stopReason") == "end_turn", reply
assert "LOCAL_ACK_WS_SHARED" in json.dumps(acp.frames)
accepted = await ws.rpc("prompt.submit", session_id=sid, input_id="after-acp-disconnect", text="WS_SHARED WS")
- async with asyncio.timeout(30):
- while True:
- receipt = await ws.rpc("prompt.receipt", session_id=sid, admission_id=accepted["admission_id"])
- if receipt["status"] == "terminal":
- assert receipt["outcome"] == "completed", receipt
- break
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 30
+ while True:
+ receipt = await ws.rpc("prompt.receipt", session_id=sid, admission_id=accepted["admission_id"])
+ if receipt["status"] == "terminal":
+ assert receipt["outcome"] == "completed", receipt
+ break
+ assert time.monotonic() < deadline, f"WS prompt never settled: {receipt}"
+ await asyncio.sleep(.05)
snapshot = await ws.rpc("session.resume", session_id=sid)
assert "WS_SHARED ACP" in json.dumps(snapshot["messages"])
assert "WS_SHARED WS" in json.dumps(snapshot["messages"])
@@ -122,9 +125,8 @@ async def test_acp_permission_detach_keeps_canonical_waiter(daemon, tmp_path, mo
prompt_task = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,
prompt=[{"type": "text", "text": "Remove the owned fixture"}]))
try:
- async with asyncio.timeout(15):
- while not any(f.get("method") == "session/request_permission" for f in acp.frames):
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: any(f.get("method") == "session/request_permission" for f in acp.frames),
+ timeout=15, what="the ACP permission request")
permission = next(f for f in acp.frames if f.get("method") == "session/request_permission")
assert target.exists()
snapshot = await ws.rpc("session.resume", session_id=sid)
@@ -141,9 +143,7 @@ async def test_acp_permission_detach_keeps_canonical_waiter(daemon, tmp_path, mo
response = await ws.rpc("approval.respond", session_id=sid, prompt_id=pending["prompt_id"],
execution_generation=pending["execution_generation"], choice="once")
assert response["status"] == "resolved", response
- async with asyncio.timeout(20):
- while target.exists():
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: not target.exists(), timeout=20, what="the approved deletion")
print("ACP_PERMISSION_RECEIPT=" + json.dumps({"session_id": sid, "permission": permission,
"stale_generation_rejected": True, "detached_waiter_resolved_by_ws": True,
"real_owned_deletion": not target.exists()}))
diff --git a/tests/acp_adapter/test_gateway_wire_controls.py b/tests/acp_adapter/test_gateway_wire_controls.py
index 0c40b1b0bc9..a863abcc583 100644
--- a/tests/acp_adapter/test_gateway_wire_controls.py
+++ b/tests/acp_adapter/test_gateway_wire_controls.py
@@ -9,6 +9,7 @@ import pytest
from acp_adapter.server import HermesACPAgent
from hermes_cli.gateway_client import GatewayClientError
from tests.acp_adapter.test_gateway_sessions import editor, viewer
+from tests.waiting import async_wait_until
@pytest.mark.platforms("linux")
@@ -44,9 +45,8 @@ async def test_real_acp_answer_resolves_the_exact_pending_control(daemon, tmp_pa
task = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,
prompt=[{"type": "text", "text": "Remove owned fixture after consent"}]))
try:
- async with asyncio.timeout(15):
- while not any(f.get("method") == "session/request_permission" for f in acp.frames):
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: any(f.get("method") == "session/request_permission" for f in acp.frames),
+ timeout=15, what="the ACP permission request")
permission = next(f for f in acp.frames if f.get("method") == "session/request_permission")
assert target.exists()
pending = (await ws.rpc("session.resume", session_id=sid))["prompts"][0]
diff --git a/tests/gateway/fixtures/bot_authority_peer.py b/tests/gateway/fixtures/bot_authority_peer.py
index 5f195b52aea..3f14855e2b6 100644
--- a/tests/gateway/fixtures/bot_authority_peer.py
+++ b/tests/gateway/fixtures/bot_authority_peer.py
@@ -10,6 +10,7 @@ import threading
from automation_peer import Model
from local_recovery_probe import daemon, websocket, rpc
+from tests.waiting import async_wait_until
def probe(base):
@@ -34,9 +35,7 @@ def probe(base):
return [dict(r) for r in db.execute('SELECT * FROM session_admissions ORDER BY seq')]
async def wait(predicate):
- async with asyncio.timeout(30):
- while not predicate():
- await asyncio.sleep(.05)
+ await async_wait_until(predicate, timeout=30, interval=.05)
async def run(desc):
async with websocket(home, desc) as ws:
diff --git a/tests/gateway/fixtures/local_lineage_probe.py b/tests/gateway/fixtures/local_lineage_probe.py
index 270be22992b..716f7853228 100644
--- a/tests/gateway/fixtures/local_lineage_probe.py
+++ b/tests/gateway/fixtures/local_lineage_probe.py
@@ -8,6 +8,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 probe(tmp_path):
@@ -34,9 +35,8 @@ def probe(tmp_path):
with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
return dict(db.execute('SELECT request_id,status FROM session_admissions'))
async def terminal(request_id):
- async with asyncio.timeout(30):
- while db_rows().get(request_id) != 'terminal':
- await asyncio.sleep(.03)
+ await async_wait_until(lambda: db_rows().get(request_id) == 'terminal', timeout=30, interval=.03,
+ what=f'{request_id} to settle')
async def first(desc, proc):
async with websocket(home, desc) as ws:
for name in ('safe', 'reset', 'unknown', 'foreign'):
@@ -57,15 +57,15 @@ def probe(tmp_path):
await ws.send(json.dumps({'id': 'crash', 'method': 'prompt.submit', 'params': {
'session_id': sessions['safe'], 'input_id': 'safe', 'text': 'RECOVER_SAFE'}}))
# Wait for the actual publication, not just admission before the fixture ran.
- async with asyncio.timeout(20):
- while True:
- with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
- ended = dict(db.execute('SELECT id,end_reason FROM sessions'))
- if all(ended.get(sessions[n]) == reason for n, reason in
- [('safe', 'compression'), ('reset', 'session_reset'), ('unknown', 'compression')]):
- break
- assert proc.poll() is None
- await asyncio.sleep(.03)
+ def published():
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ ended = dict(db.execute('SELECT id,end_reason FROM sessions'))
+ if all(ended.get(sessions[n]) == reason for n, reason in
+ [('safe', 'compression'), ('reset', 'session_reset'), ('unknown', 'compression')]):
+ return True
+ assert proc.poll() is None
+ return False
+ await async_wait_until(published, timeout=20, interval=.03, what='the lineage publications')
proc.kill()
await asyncio.to_thread(proc.wait, 10)
async def recovered(desc):
diff --git a/tests/gateway/fixtures/native_ingress_media_peer.py b/tests/gateway/fixtures/native_ingress_media_peer.py
index a161731593f..487b3ec1eb2 100644
--- a/tests/gateway/fixtures/native_ingress_media_peer.py
+++ b/tests/gateway/fixtures/native_ingress_media_peer.py
@@ -10,6 +10,7 @@ import threading
import traceback
from shared_authority_peer import ModelPeer
+from tests.waiting import wait_until
async def probe(mode, peer):
@@ -116,8 +117,10 @@ async def probe(mode, peer):
# Published by rename: the parent SIGKILLs this process the moment the file exists.
(state / 'accepted.tmp').write_text(json.dumps(evidence))
os.replace(state / 'accepted.tmp', state / 'accepted.json')
- threading.Event().wait(60)
- raise AssertionError('parent failed to kill owner')
+ # Hang until the parent's SIGKILL lands; a parent that exits instead orphans us (reparent).
+ parent = os.getppid()
+ wait_until(lambda: os.getppid() != parent, timeout=60, interval=.05, what='the parent to kill this owner')
+ raise AssertionError('parent exited without killing owner')
if mode == 'recover':
before = json.loads((state / 'accepted.json').read_text())
diff --git a/tests/gateway/test_api_crash_recovery.py b/tests/gateway/test_api_crash_recovery.py
index ccab9f057a2..a0ff847d571 100644
--- a/tests/gateway/test_api_crash_recovery.py
+++ b/tests/gateway/test_api_crash_recovery.py
@@ -11,6 +11,7 @@ import threading
import aiohttp
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, Model
+from tests.waiting import async_wait_until
def test_api_crash_queue_and_identified_result_retry(tmp_path):
@@ -77,9 +78,8 @@ def test_api_crash_queue_and_identified_result_retry(tmp_path):
async def restarted():
async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=8)) as client:
- async with asyncio.timeout(20):
- while rows()[runs['safe']] != 'terminal':
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: rows()[runs['safe']] == 'terminal', timeout=20, interval=.05,
+ what='the recovered safe run to settle')
assert rows()[runs['started']] == 'unknown' and rows()[runs['follower']] == 'queued', rows()
async with client.post(url + '/chat/completions',
json={'messages': [{'role': 'user', 'content': 'BLOCK_STARTED'}]},
diff --git a/tests/gateway/test_bot_mailbox_async.py b/tests/gateway/test_bot_mailbox_async.py
index 0daa9167555..7a4708c9634 100644
--- a/tests/gateway/test_bot_mailbox_async.py
+++ b/tests/gateway/test_bot_mailbox_async.py
@@ -1,6 +1,7 @@
"""Bot receipt polling is local and mailbox serialization never parks the event loop."""
import asyncio
import threading
+import time
import pytest
@@ -72,9 +73,10 @@ async def test_paused_receipt_rearms_on_resume_without_polling_rpc(bot, monkeypa
monkeypatch.setattr(bot.authority, '_schedule', schedule)
schedule(ref)
await bot.authority.sessions[ref.session_id].task
- async with asyncio.timeout(5):
- while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':
- await asyncio.sleep(.01)
+ deadline = time.monotonic() + 5
+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':
+ assert time.monotonic() < deadline, 'the paused delivery never settled'
+ await asyncio.sleep(.01)
assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['reply'] == 'pong'
@@ -113,9 +115,10 @@ async def test_adopted_result_during_unknown_projection_is_not_lost(bot, monkeyp
generation=row['generation'], outcome='completed', result={'result': {'final_response': 'adopted reply'}, 'usage': {}})
bot.authority._publish_pending(ref)
release.set()
- async with asyncio.timeout(5):
- while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'ambiguous':
- await asyncio.sleep(.01)
+ deadline = time.monotonic() + 5
+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'ambiguous':
+ assert time.monotonic() < deadline, 'the adopted delivery stayed ambiguous'
+ await asyncio.sleep(.01)
assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'settled'
assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['reply'] == 'adopted reply'
finally:
@@ -155,7 +158,8 @@ async def test_drain_defers_retry_without_publishing_interim_failure(bot, monkey
monkeypatch.setattr(finite, 'execute_finite_admission', execute)
bot.authority.runner._draining = False
await recover_bot_deliveries(bot.authority)
- async with asyncio.timeout(5):
- while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':
- await asyncio.sleep(.01)
+ deadline = time.monotonic() + 5
+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':
+ assert time.monotonic() < deadline, 'the recovered delivery never settled'
+ await asyncio.sleep(.01)
assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['retry_admission_id']
diff --git a/tests/gateway/test_ingress_admission_off_loop.py b/tests/gateway/test_ingress_admission_off_loop.py
index 10107c6384f..ed734c88c91 100644
--- a/tests/gateway/test_ingress_admission_off_loop.py
+++ b/tests/gateway/test_ingress_admission_off_loop.py
@@ -45,12 +45,14 @@ async def test_ingress_admission_never_blocks_the_owner_loop_on_a_held_writer(tm
assert await asyncio.to_thread(held.wait, 10)
try:
task = asyncio.create_task(admit())
- ticks, start = 0, time.monotonic()
- while time.monotonic() - start < 1.0:
+ # A loop parked in a blocking BEGIN IMMEDIATE runs no ticks until the writer lets go (held
+ # 30 s here; the store's write patience is 20 s), so no gap between ticks reaches 2 s.
+ ticks, last = 0, time.monotonic()
+ while ticks < 10:
await asyncio.sleep(0.05)
ticks += 1
- # A loop parked in a blocking BEGIN IMMEDIATE runs no ticks until the writer lets go.
- assert ticks >= 10, f'owner loop stalled behind the held writer ({ticks} ticks in 1s)'
+ gap, last = time.monotonic() - last, time.monotonic()
+ assert gap < 2.0, f'owner loop stalled behind the held writer ({gap:.1f}s before tick {ticks})'
assert not task.done(), 'the admission must wait for the writer, not skip the commit'
finally:
release.set()
diff --git a/tests/gateway/test_managed_worker_background_output.py b/tests/gateway/test_managed_worker_background_output.py
index 145f0edef42..d222b7d7439 100644
--- a/tests/gateway/test_managed_worker_background_output.py
+++ b/tests/gateway/test_managed_worker_background_output.py
@@ -20,6 +20,8 @@ import threading
import pytest
+from tests.waiting import async_wait_until
+
ROOT = Path(__file__).resolve().parents[2]
COMMAND = 'sleep 2; echo FIRST_$((40+2)); sleep 1; echo SECOND_$((6*7)); (exit 7)'
@@ -119,9 +121,8 @@ def test_next_managed_turn_reads_the_previous_workers_background_output(tmp_path
sid = created['result']['session_id']
for request_id, text in (('start', 'START'), ('wait', 'WAIT')):
assert 'result' in await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text=text)
- async with asyncio.timeout(90):
- while not settled(request_id):
- await asyncio.sleep(.1)
+ await async_wait_until(lambda: settled(request_id), timeout=90, interval=.1,
+ what=f'{request_id} 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_retired_authority_cron_fence.py b/tests/gateway/test_retired_authority_cron_fence.py
index 8e94e298a73..4cda1bfd73a 100644
--- a/tests/gateway/test_retired_authority_cron_fence.py
+++ b/tests/gateway/test_retired_authority_cron_fence.py
@@ -81,5 +81,5 @@ async def test_retired_authority_refuses_writes_before_successor_epoch(tmp_path,
await call(authority, receipt)
assert untouched(db, tmp_path)
finally:
- await asyncio.sleep(.05)
+ await asyncio.sleep(0) # a yield for done-callbacks; retirement already joined every task and thread
db.close()