Skip to content

The agent that grows with you

test(hx013): wait for conditions, not the clock, in gateway daemon probes

Teknium23ecdd3cf69e
diff --git a/tests/gateway/fixtures/ancillary_reads_peer.py b/tests/gateway/fixtures/ancillary_reads_peer.py
index 630b360266d..f9e7f2c7fa5 100644
--- a/tests/gateway/fixtures/ancillary_reads_peer.py
+++ b/tests/gateway/fixtures/ancillary_reads_peer.py
@@ -113,9 +113,9 @@ async def probe(mode):
for task, route in [(sid, live.route), ('foreign', live.route), (sid, 'wrong-route')]:
processes.append(process_registry.spawn_local(command, cwd=str(home), task_id=task,
owner_task_id=task, session_key=route))
- async with asyncio.timeout(10):
- while any('PROCESS_OWNED' not in p.output_buffer for p in processes):
- await asyncio.sleep(.02)
+ from tests.waiting import async_wait_until
+ await async_wait_until(lambda: all('PROCESS_OWNED' in p.output_buffer for p in processes),
+ timeout=10, what='every owned process printed PROCESS_OWNED')
process_result = await rpc(ws, 'process.list', session_id=sid)
rows = process_result.get('result', {}).get('processes')
assert rows and [p['session_id'] for p in rows] == [processes[0].id], process_result
diff --git a/tests/gateway/fixtures/config_policy_recovery_probe.py b/tests/gateway/fixtures/config_policy_recovery_probe.py
index 23188e14fb2..c32c417cb36 100644
--- a/tests/gateway/fixtures/config_policy_recovery_probe.py
+++ b/tests/gateway/fixtures/config_policy_recovery_probe.py
@@ -51,13 +51,15 @@ def probe(tmp_path):
epoch = resumed['result']['replay_epoch']
accepted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=phase + side, text=phase + side)
assert 'result' in accepted, accepted
- async with asyncio.timeout(30):
- while True:
- receipt = await rpc(ws, 'prompt.receipt', session_id=sid,
- admission_id=accepted['result']['admission_id'])
- if receipt['result']['status'] == 'terminal':
- break
- await asyncio.sleep(.03)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + 30
+ while True:
+ receipt = await rpc(ws, 'prompt.receipt', session_id=sid,
+ admission_id=accepted['result']['admission_id'])
+ if receipt['result']['status'] == 'terminal':
+ break
+ assert loop.time() < deadline, ('admission never settled', receipt)
+ await asyncio.sleep(.03)
events = await rpc(ws, 'session.events.since', session_id=sid, last_sequence=0, replay_epoch=epoch)
if phase == 'denied':
# This baseline's pre-agent display failure has generic public
diff --git a/tests/gateway/fixtures/control_boundaries.py b/tests/gateway/fixtures/control_boundaries.py
index ed031814bec..4c2a8dc08cd 100644
--- a/tests/gateway/fixtures/control_boundaries.py
+++ b/tests/gateway/fixtures/control_boundaries.py
@@ -48,12 +48,14 @@ async def exercise_control_boundaries(tmp_path, monkeypatch):
turn = TurnRunner(SimpleNamespace(session_authority=authority), ctx)
async def wait_prompt():
- async with asyncio.timeout(5):
- while True:
- snapshot = await authority.attach(actor, ref)
- if snapshot.prompts:
- return snapshot.prompts[-1]
- await asyncio.sleep(.01)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + 5
+ while True:
+ snapshot = await authority.attach(actor, ref)
+ if snapshot.prompts:
+ return snapshot.prompts[-1]
+ assert loop.time() < deadline, 'no approval prompt was published'
+ await asyncio.sleep(.01)
tasks = []
try:
@@ -62,9 +64,10 @@ async def exercise_control_boundaries(tmp_path, monkeypatch):
turn._approval_notify_sync, {'command': f'owned-command-{n}', 'description': 'fixture',
'allow_session': False, 'allow_permanent': False, 'pattern_keys': [str(n)]}))
tasks.append(task)
- async with asyncio.timeout(5):
- while len((await authority.attach(actor, ref)).prompts) < n + 1:
- await asyncio.sleep(.01)
+ loop, deadline = asyncio.get_running_loop(), asyncio.get_running_loop().time() + 5
+ while len((await authority.attach(actor, ref)).prompts) < n + 1:
+ assert loop.time() < deadline, f'approval prompt {n} was never published'
+ await asyncio.sleep(.01)
prompts = (await authority.attach(actor, ref)).prompts
import pytest
for bad_actor, bad_ref, gen, reason in [
diff --git a/tests/gateway/fixtures/native_ingress_trust_peer.py b/tests/gateway/fixtures/native_ingress_trust_peer.py
index 338934c60e1..135fffb235c 100644
--- a/tests/gateway/fixtures/native_ingress_trust_peer.py
+++ b/tests/gateway/fixtures/native_ingress_trust_peer.py
@@ -9,6 +9,7 @@ import threading
import traceback
from shared_authority_peer import ModelPeer
+from tests.waiting import async_wait_until
async def probe(mode, peer):
@@ -78,9 +79,8 @@ async def probe(mode, peer):
hostile = adapter.build_source(chat_id='forged-profile', chat_type='dm', user_id='fixture-user')
hostile.profile = 'foreign'
await adapter.handle_message(MessageEvent(text='FORGED_PROFILE', source=hostile, message_id='foreign-profile'))
- 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 forged-profile message to finish')
assert not authority.sessions, 'unrouted profile field became durable authority'
print(json.dumps({'rejected': rejected}))
return
@@ -94,9 +94,7 @@ async def probe(mode, peer):
accepted = admit_session_input(authority.db, epoch=authority.epoch, principal_id='messaging:' + identity,
session_id=ref.session_id, request_id='trust-1', payload=payload)
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 trusted turn to finish')
entry = runner.session_store.get_or_create_session(source)
rows = list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False)
assert rows and rows[0]['status'] == 'terminal' and rows[0]['outcome'] == 'completed', (rows, adapter.deliveries)
@@ -107,9 +105,7 @@ async def probe(mode, peer):
fresh = MessageEvent(text='FRESH_CALLBACK_INPUT', source=adapter.build_source(
chat_id='trust-chat', chat_type='dm', user_id='fixture-user'), message_id='trust-2')
await adapter.handle_message(fresh)
- 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 fresh turn to finish')
rows = list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False)
assert len(rows) == 2 and 'provenance' in rows[1]['payload']['native_text_v1'], rows
assert all(row['outcome'] == 'completed' for row in rows) and len(peer.requests) == 2
diff --git a/tests/gateway/fixtures/operator_cross_surface_peer.py b/tests/gateway/fixtures/operator_cross_surface_peer.py
index 4b885846116..eeb31875d54 100644
--- a/tests/gateway/fixtures/operator_cross_surface_peer.py
+++ b/tests/gateway/fixtures/operator_cross_surface_peer.py
@@ -9,6 +9,7 @@ import threading
import traceback
from tests.gateway.fixtures.shared_authority_peer import ModelPeer
+from tests.waiting import async_wait_until
async def probe(peer, creator):
@@ -149,12 +150,10 @@ async def probe(peer, creator):
assert (await rpc(viewer, 'session.resume', session_id=sid))['stored_session_id'] == sid
assert await rpc(viewer, 'prompt.submit', **followup) == accepted
peer.release.set()
- async with asyncio.timeout(45):
- while True:
- rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
- if len(rows) == 2 and all(row['status'] == 'terminal' for row in rows):
- break
- await asyncio.sleep(.05)
+ def settled():
+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
+ return rows if len(rows) == 2 and all(row['status'] == 'terminal' for row in rows) else None
+ rows = await async_wait_until(settled, timeout=45, what='both admissions terminal')
assert [row['principal_id'] for row in rows] == attribution
assert local_receipt(authority.db, sid)['principal_id'] == original_owner
messages = authority.db.get_messages_as_conversation(sid)
diff --git a/tests/gateway/test_api_pending_daemon.py b/tests/gateway/test_api_pending_daemon.py
index 8ef551586f2..610a80795df 100644
--- a/tests/gateway/test_api_pending_daemon.py
+++ b/tests/gateway/test_api_pending_daemon.py
@@ -84,13 +84,15 @@ def test_api_and_ws_pending_controls_share_identity(tmp_path):
run = accepted['run_id']
async with websocket(home, desc) as ws:
prompt = None
- async with asyncio.timeout(15):
- while not prompt:
- resumed = await rpc(ws, 'session.resume', session_id='api-controls')
- assert 'result' in resumed, resumed
- prompt = next((p for p in resumed['result'].get('prompts', []) if p['kind'] == kind), None)
- if not prompt:
- await asyncio.sleep(.05)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + 15
+ while not prompt:
+ resumed = await rpc(ws, 'session.resume', session_id='api-controls')
+ assert 'result' in resumed, resumed
+ prompt = next((p for p in resumed['result'].get('prompts', []) if p['kind'] == kind), None)
+ if not prompt:
+ assert loop.time() < deadline, ('no pending ' + kind, resumed)
+ await asyncio.sleep(.05)
async with client.get(url + '/' + run) as response:
projected = await response.json()
assert projected['pending_controls'] == [prompt], projected
@@ -109,13 +111,15 @@ def test_api_and_ws_pending_controls_share_identity(tmp_path):
session_id='api-controls', execution_generation=body['execution_generation'],
prompt_id=body['request_id'], **({'choice': 'once'} if kind == 'approval' else {'answer': 'GREEN'}))
assert 'error' in late or late['result']['status'] == 'already_resolved', late
- async with asyncio.timeout(20):
- while True:
- async with client.get(url + '/' + run) as response:
- final = await response.json()
- if final['status'] == 'completed':
- break
- await asyncio.sleep(.05)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + 20
+ while True:
+ async with client.get(url + '/' + run) as response:
+ final = await response.json()
+ if final['status'] == 'completed':
+ break
+ assert loop.time() < deadline, ('run never completed', final)
+ await asyncio.sleep(.05)
assert (await post(path, body))[0] == 409
assert not peer.target.exists()
tools = [m for req in peer.requests for m in req.get('messages', []) if m['role'] == 'tool']
diff --git a/tests/gateway/test_journey_new_session_queued_work.py b/tests/gateway/test_journey_new_session_queued_work.py
index fdb7e711533..c0d9b90ee1c 100644
--- a/tests/gateway/test_journey_new_session_queued_work.py
+++ b/tests/gateway/test_journey_new_session_queued_work.py
@@ -22,6 +22,7 @@ import threading
import pytest
from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
A_FOLLOWERS = ('A_FOLLOWER_1', 'A_FOLLOWER_2')
@@ -65,9 +66,7 @@ def test_new_session_never_absorbs_or_drops_earlier_queued_work(tmp_path, restar
return [[m.get('content') for m in r['messages'] if m['role'] == 'user'] for r in peer.requests]
async def until(predicate, timeout=30):
- async with asyncio.timeout(timeout):
- while not predicate():
- await asyncio.sleep(.03)
+ await async_wait_until(predicate, timeout=timeout, interval=.03)
ids = {}
diff --git a/tests/gateway/test_managed_worker_construct.py b/tests/gateway/test_managed_worker_construct.py
index 9cd70dd0138..989a6c3fbb9 100644
--- a/tests/gateway/test_managed_worker_construct.py
+++ b/tests/gateway/test_managed_worker_construct.py
@@ -19,6 +19,7 @@ from types import SimpleNamespace
import pytest
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+from tests.waiting import async_wait_until
def _reply(handler, body, text):
@@ -99,9 +100,9 @@ def run_pair(tmp_path, extra_config, turn, **create_params):
async def settle(ws, sid, request_id, text):
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text=text)
assert 'result' in submitted, submitted
- async with asyncio.timeout(120):
- while query('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)) != [('terminal',)]:
- await asyncio.sleep(.05)
+ await async_wait_until(
+ lambda: query('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)) == [('terminal',)],
+ timeout=120, interval=.05, what=f'admission {request_id} terminal')
[(admission,)] = query('SELECT admission_id FROM session_admissions WHERE request_id=?', (request_id,))
receipt = await rpc(ws, 'prompt.receipt', session_id=sid, admission_id=admission, include_result=True)
return receipt['result']['result']
diff --git a/tests/gateway/test_native_startup_recovery.py b/tests/gateway/test_native_startup_recovery.py
index b1f91b09117..b2322786b66 100644
--- a/tests/gateway/test_native_startup_recovery.py
+++ b/tests/gateway/test_native_startup_recovery.py
@@ -13,6 +13,7 @@ import threading
import aiohttp
from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon
+from tests.waiting import async_wait_until
def test_native_queue_recovers_only_after_current_adapter_publication(tmp_path):
@@ -50,9 +51,8 @@ def test_native_queue_recovers_only_after_current_adapter_publication(tmp_path):
assert response.status == 202, await response.text()
assert rows() == {'safe': 'queued'}
async def settled():
- async with asyncio.timeout(25):
- while rows()['safe'] != 'terminal':
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: rows()['safe'] == 'terminal', timeout=25, interval=.05,
+ what='the recovered admission to settle')
evidence = []
try:
with daemon(root, home, env, barrier=True, fixture='api_recovery_daemon.py') as (proc, desc):
diff --git a/tests/hermes_cli/test_runtime_maintenance_exclusion.py b/tests/hermes_cli/test_runtime_maintenance_exclusion.py
index 12528c877d8..a35a3e46e60 100644
--- a/tests/hermes_cli/test_runtime_maintenance_exclusion.py
+++ b/tests/hermes_cli/test_runtime_maintenance_exclusion.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 test_restore_refuses_live_authority_without_changing_data(tmp_path):
@@ -42,9 +43,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')