Skip to content

The agent that grows with you

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

Teknium4b38ef106e92
diff --git a/tests/acp_adapter/test_retained_identity_retirement.py b/tests/acp_adapter/test_retained_identity_retirement.py
index e343a3e0915..cebd1bf41f6 100644
--- a/tests/acp_adapter/test_retained_identity_retirement.py
+++ b/tests/acp_adapter/test_retained_identity_retirement.py
@@ -14,6 +14,7 @@ import pytest_asyncio
from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
from hermes_state_runtime import list_session_admissions
+from tests.waiting import async_wait_until
LOST = 'Gateway disconnected; turn outcome is unknown.'
@@ -94,10 +95,9 @@ async def _acp(owner):
async def _settled(owner, count):
- async with asyncio.timeout(5):
- while sum(row['status'] == 'terminal' for row in list_session_admissions(
- owner.authority.db, session_id=owner.sid, pending_only=False)) < count:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: sum(row['status'] == 'terminal' for row in list_session_admissions(
+ owner.authority.db, session_id=owner.sid, pending_only=False)) >= count,
+ timeout=5, what=f'{count} terminal admissions')
def _surface(name, owner):
diff --git a/tests/gateway/fixtures/api_authority_peer.py b/tests/gateway/fixtures/api_authority_peer.py
index 4b8dfad2aae..66cf9b7f783 100644
--- a/tests/gateway/fixtures/api_authority_peer.py
+++ b/tests/gateway/fixtures/api_authority_peer.py
@@ -5,21 +5,24 @@ import os
from pathlib import Path
import sys
import threading
+import time
import traceback
from http.server import ThreadingHTTPServer
from shared_authority_peer import ModelPeer
+from tests.waiting import async_wait_until
async def _poll_run_terminal(client, url, headers):
"""Poll a /v1/runs status URL until the run reaches a terminal status (20 s budget)."""
- async with asyncio.timeout(20):
- while True:
- async with client.get(url, headers=headers) as response:
- status = await response.json()
- if status.get('status') in ('completed', 'failed', 'cancelled'):
- return status
- await asyncio.sleep(.02)
+ deadline = time.monotonic() + 20
+ while True:
+ async with client.get(url, headers=headers) as response:
+ status = await response.json()
+ if status.get('status') in ('completed', 'failed', 'cancelled'):
+ return status
+ assert time.monotonic() < deadline, ('run never reached a terminal status', status)
+ await asyncio.sleep(.02)
async def probe(peer):
@@ -128,9 +131,8 @@ async def probe(peer):
assert response.status == 200, text
return text
pending = asyncio.create_task(request_follow())
- async with asyncio.timeout(10):
- while not any(r['payload'].get('text') == 'FIFO_SECOND' for r in list_session_admissions(authority.db, session_id=ref.session_id)):
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: any(r['payload'].get('text') == 'FIFO_SECOND' for r in list_session_admissions(
+ authority.db, session_id=ref.session_id)), timeout=10, what='FIFO_SECOND admitted')
peer.release.set()
first_reply = json.loads(await pending)
assert first_reply['choices'][0]['message']['content']
diff --git a/tests/gateway/fixtures/cli_launch_policy_probe.py b/tests/gateway/fixtures/cli_launch_policy_probe.py
index e55d9cdeeed..ba5ec527798 100644
--- a/tests/gateway/fixtures/cli_launch_policy_probe.py
+++ b/tests/gateway/fixtures/cli_launch_policy_probe.py
@@ -9,6 +9,7 @@ import re
import subprocess
import sys
import threading
+import time
from tests.gateway.fixtures.local_recovery_probe import daemon, websocket, rpc
@@ -135,12 +136,13 @@ def probe(tmp_path):
result = await rpc(ws, 'prompt.submit', session_id=sid, input_id='restart-' + side, text='NEVER_INFER')
assert 'result' in result, result
admission = result['result']['admission_id']
- async with asyncio.timeout(20):
- while True:
- result = await rpc(ws, 'prompt.receipt', session_id=sid, admission_id=admission)
- if result['result']['status'] == 'terminal':
- break
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 20
+ while True:
+ result = await rpc(ws, 'prompt.receipt', session_id=sid, admission_id=admission)
+ if result['result']['status'] == 'terminal':
+ break
+ assert time.monotonic() < deadline, result
+ await asyncio.sleep(.05)
events = await rpc(ws, 'session.events.since', session_id=sid, last_sequence=0, replay_epoch=replay_epoch)
assert 'launch_credentials_unavailable' in json.dumps(events), events
diff --git a/tests/gateway/fixtures/local_recovery_probe.py b/tests/gateway/fixtures/local_recovery_probe.py
index 65516ddf5ff..336a95712b7 100644
--- a/tests/gateway/fixtures/local_recovery_probe.py
+++ b/tests/gateway/fixtures/local_recovery_probe.py
@@ -14,6 +14,7 @@ import time
from websockets.asyncio.client import connect
from tests.gateway.test_normal_runtime_boot import control
+from tests.waiting import async_wait_until
class Model(BaseHTTPRequestHandler):
@@ -125,9 +126,7 @@ def probe(tmp_path):
sessions[name] = result['result']['session_id']
warm = await rpc(ws, 'prompt.submit', session_id=sessions['safe'], input_id='warm', text='WARM_HISTORY')
assert warm['result']['status'] == 'queued', warm
- async with asyncio.timeout(30):
- while rows().get('warm') != 'terminal':
- await asyncio.sleep(.02)
+ await async_wait_until(lambda: rows().get('warm') == 'terminal', timeout=30, what='warm turn terminal')
await rpc(ws, 'prompt.submit', session_id=sessions['unknown'], input_id='started', text='BLOCK_STARTED')
assert await asyncio.to_thread(peer.blocked.wait, 20)
await rpc(ws, 'prompt.submit', session_id=sessions['unknown'], input_id='follower', text='NEVER_REPLAY')
@@ -136,17 +135,14 @@ def probe(tmp_path):
# The daemon stops itself immediately after this admission commits.
await ws.send(json.dumps({'id': 'kill-boundary', 'method': 'prompt.submit', 'params': {
'session_id': sessions['safe'], 'input_id': 'safe', 'text': 'RECOVER_QUEUED'}}))
- async with asyncio.timeout(20):
- while rows().get('safe') != 'queued':
- await asyncio.sleep(.02)
+ await async_wait_until(lambda: rows().get('safe') == 'queued', timeout=20, what='safe admission queued')
assert rows()['foreign'] == 'queued', rows()
proc.kill()
await asyncio.to_thread(proc.wait, 10)
async def second(desc):
async with websocket(home, desc) as ws:
- async with asyncio.timeout(35):
- while rows().get('safe') != 'terminal':
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: rows().get('safe') == 'terminal', timeout=35, interval=.05,
+ what='recovered safe admission terminal')
result = await rpc(ws, 'session.resume', session_id=sessions['safe'])
assert 'result' in result, result
history = json.dumps(result['result']['messages'])
diff --git a/tests/gateway/fixtures/native_role_peer.py b/tests/gateway/fixtures/native_role_peer.py
index 8c6d6eb6c8b..49c6f05736e 100644
--- a/tests/gateway/fixtures/native_role_peer.py
+++ b/tests/gateway/fixtures/native_role_peer.py
@@ -10,6 +10,7 @@ import traceback
from types import SimpleNamespace
from shared_authority_peer import ModelPeer
+from tests.waiting import async_wait_until
async def probe(peer):
@@ -71,9 +72,7 @@ async def probe(peer):
async def send(ev):
await adapter.handle_message(ev)
- 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='adapter sessions idle')
if sys.argv[1] == 'multiplex':
from agent.secret_scope import set_multiplex_active
diff --git a/tests/gateway/fixtures/shared_authority_recovery.py b/tests/gateway/fixtures/shared_authority_recovery.py
index f4eb769fdec..532e73ce725 100644
--- a/tests/gateway/fixtures/shared_authority_recovery.py
+++ b/tests/gateway/fixtures/shared_authority_recovery.py
@@ -4,10 +4,10 @@ from dataclasses import replace
import json
import os
from pathlib import Path
-import threading
from gateway.platforms.event import MessageEvent
from hermes_state_runtime import list_session_admissions
+from tests.waiting import async_wait_until, wait_until
def rows(authority, sid):
@@ -54,9 +54,8 @@ async def prepare_crash(runner, adapter, source, peer):
sid = authority.register(source).session_id
follower = asyncio.create_task(adapter.handle_message(MessageEvent(
text='UNKNOWN_FOLLOWER', source=source, message_id='unknown-follower')))
- async with asyncio.timeout(5):
- while not any(r['request_id'] == 'unknown-follower' for r in rows(authority, sid)):
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: any(r['request_id'] == 'unknown-follower' for r in rows(authority, sid)),
+ timeout=5, what='unknown-follower committed')
# The receive coroutine is released at durable commit (serial IRC/Signal loops keep
# reading); the follower itself stays queued behind the started head until the crash.
await asyncio.wait_for(follower, 5)
@@ -76,8 +75,10 @@ async def prepare_crash(runner, adapter, source, peer):
ready = Path(os.environ['HERMES_HOME'], 'crash-ready.json')
ready.with_suffix('.tmp').write_text(json.dumps(evidence))
os.replace(ready.with_suffix('.tmp'), ready)
- threading.Event().wait(60)
- raise AssertionError('parent did not kill the actual owner')
+ # Hold the loop frozen until the parent's SIGKILL; end early if the parent itself went away.
+ parent = os.getppid()
+ wait_until(lambda: os.getppid() != parent, timeout=60, interval=.05, what='the parent to SIGKILL this owner')
+ raise AssertionError('parent exited without killing the actual owner')
async def recover_probe(runner, adapter, source, peer):
diff --git a/tests/gateway/test_api_hosted_daemon.py b/tests/gateway/test_api_hosted_daemon.py
index ab62bb3cc36..202c7e5bef5 100644
--- a/tests/gateway/test_api_hosted_daemon.py
+++ b/tests/gateway/test_api_hosted_daemon.py
@@ -8,6 +8,7 @@ from pathlib import Path
import socket
import sqlite3
import threading
+import time
import aiohttp
@@ -67,14 +68,15 @@ def test_hosted_grant_inference_survives_owner_restart(tmp_path):
assert accepted['run_id'] == run_ids[task] and accepted['replayed'], accepted
assert len(peer.requests) == before
run_ids[task] = accepted['run_id']
- async with asyncio.timeout(20):
- while True:
- async with client.get(url + '/runs/' + run_ids[task], headers=headers) as response:
- result = await response.json()
- assert response.status == 200, result
- if result['status'] in {'completed', 'failed'}:
- break
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 20
+ while True:
+ async with client.get(url + '/runs/' + run_ids[task], headers=headers) as response:
+ result = await response.json()
+ assert response.status == 200, result
+ if result['status'] in {'completed', 'failed'}:
+ break
+ assert time.monotonic() < deadline, ('run never settled', result)
+ await asyncio.sleep(.05)
assert result['status'] == 'completed' and prompt in result['output'], result
sessions.append(result['session_id'])
async with client.get(url + '/runs/' + run_ids[1], headers={'Authorization': 'HermesRoom invalid'}) as response:
diff --git a/tests/gateway/test_journey_compress_restart_fifo.py b/tests/gateway/test_journey_compress_restart_fifo.py
index 3123ffb1650..8a36865de19 100644
--- a/tests/gateway/test_journey_compress_restart_fifo.py
+++ b/tests/gateway/test_journey_compress_restart_fifo.py
@@ -18,6 +18,7 @@ import threading
import pytest
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
FOLLOWERS = ('FOLLOWER_1', 'FOLLOWER_2', 'FOLLOWER_3')
@@ -120,9 +121,7 @@ def test_followers_survive_compression_and_restart_in_order_exactly_once(tmp_pat
return reply['result']
async def wait_rows(predicate, timeout=40):
- async with asyncio.timeout(timeout):
- while not predicate():
- await asyncio.sleep(.03)
+ await async_wait_until(predicate, timeout=timeout, interval=.03, what='admission rows')
async def first(desc, owner):
async with websocket(home, desc) as ws:
diff --git a/tests/gateway/test_journey_restart_open_prompts.py b/tests/gateway/test_journey_restart_open_prompts.py
index cb2163fc59f..ef79235df50 100644
--- a/tests/gateway/test_journey_restart_open_prompts.py
+++ b/tests/gateway/test_journey_restart_open_prompts.py
@@ -19,10 +19,12 @@ import shlex
import signal
import sqlite3
import threading
+import time
import pytest
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
FOLLOWERS = {'approval': ('APPROVAL_FOLLOWER_1', 'APPROVAL_FOLLOWER_2'),
'clarify': ('CLARIFY_FOLLOWER_1', 'CLARIFY_FOLLOWER_2')}
@@ -109,9 +111,7 @@ def test_restart_fences_open_prompts_and_never_reruns_work(tmp_path, restart):
return reply['result']
async def until(predicate, timeout=40):
- async with asyncio.timeout(timeout):
- while not predicate():
- await asyncio.sleep(.03)
+ await async_wait_until(predicate, timeout=timeout, interval=.03, what='admission rows')
async def answer(ws, sid, prompt):
kind = prompt['kind']
@@ -131,10 +131,12 @@ def test_restart_fences_open_prompts_and_never_reruns_work(tmp_path, restart):
before['sessions'][kind] = sid
await call(ws, 'prompt.submit', session_id=sid, input_id=ASK[kind], text=ASK[kind])
prompt = None
- async with asyncio.timeout(30):
- while prompt is None:
- snapshot = await call(ws, 'session.resume', session_id=sid)
- prompt = next((p for p in snapshot['prompts'] if p['kind'] == kind), None)
+ deadline = time.monotonic() + 30
+ while prompt is None:
+ snapshot = await call(ws, 'session.resume', session_id=sid)
+ prompt = next((p for p in snapshot['prompts'] if p['kind'] == kind), None)
+ if prompt is None:
+ assert time.monotonic() < deadline, ('no open ' + kind + ' prompt', snapshot)
await asyncio.sleep(.03)
before['prompts'][kind] = prompt
for name in FOLLOWERS[kind]:
diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.py
index 06b5895f59a..702c87e6dbd 100644
--- a/tests/hermes_cli/test_gateway_runtime_ensure.py
+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py
@@ -5,6 +5,7 @@ import os
from pathlib import Path
import subprocess
import sys
+import threading
import time
import pytest
@@ -45,9 +46,10 @@ def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(t
payload = {"runtime_protocol": 1, "state": "starting", "instance_id": "peer",
"served_profiles": [{"profile_id": str(home), "home": str(home)}]}
stalled = False
+ unstall = threading.Event() # set at teardown so the stalled handler thread exits
def identify():
if stalled:
- time.sleep(4) # longer than the caller's deadline: a stalled owner is 'starting', never ready
+ unstall.wait(30) # outlives the caller's deadline: a stalled owner is 'starting', never ready
return payload
server = GatewayControlServer(home, verb_handlers={"identify": identify})
assert await server.start()
@@ -67,6 +69,7 @@ def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(t
assert result.state == "starting" and result.reason_code == "deadline"
assert not (home / "logs").exists()
finally:
+ unstall.set()
await server.stop()
asyncio.run(probe())