Skip to content

The agent that grows with you

test(hx013): wait for conditions, not the clock, in gateway authority tests

Teknium40b016d79ca1
diff --git a/tests/gateway/test_claim_reopen_off_loop.py b/tests/gateway/test_claim_reopen_off_loop.py
index 1504f121b6d..53bb004fedf 100644
--- a/tests/gateway/test_claim_reopen_off_loop.py
+++ b/tests/gateway/test_claim_reopen_off_loop.py
@@ -6,6 +6,8 @@ import time
import pytest
+from tests.waiting import async_wait_until
+
@pytest.mark.asyncio
async def test_reopening_a_finalized_local_row_behind_a_contended_writer_keeps_the_loop_live(tmp_path, monkeypatch):
@@ -62,16 +64,15 @@ async def test_reopening_a_finalized_local_row_behind_a_contended_writer_keeps_t
async def ticker():
last = time.monotonic()
while True:
- await asyncio.sleep(0.02)
+ await asyncio.sleep(0.02) # health: allow HX013 -- the ticker measures event-loop stalls; its fixed period IS the probe
now = time.monotonic()
gaps.append(now - last)
last = now
tick = asyncio.create_task(ticker())
try:
queued = await authority.submit(owner.actor, Submission('first', ref, {'text': 'FIRST'}, 'queue'))
- async with asyncio.timeout(10):
- while rt.get_session_admission(db, admission_id=queued.admission_id)['status'] != 'terminal':
- await asyncio.sleep(0.02)
+ await async_wait_until(lambda: rt.get_session_admission(db, admission_id=queued.admission_id)['status'] == 'terminal',
+ timeout=10, what='the first turn to settle')
assert executed == ['FIRST']
assert db.get_session(ref.session_id)['end_reason'] is None
assert max(gaps) < 0.5, f'the owner loop stalled {max(gaps):.2f}s behind the reopen writer'
diff --git a/tests/gateway/test_internal_wake_never_interrupts.py b/tests/gateway/test_internal_wake_never_interrupts.py
index 0871a7cd2e9..567673aa05b 100644
--- a/tests/gateway/test_internal_wake_never_interrupts.py
+++ b/tests/gateway/test_internal_wake_never_interrupts.py
@@ -11,6 +11,8 @@ import asyncio
import pytest
+from tests.waiting import async_wait_until
+
@pytest.mark.asyncio
async def test_kanban_wake_during_an_admitted_turn_queues_without_interrupting(monkeypatch):
@@ -64,16 +66,13 @@ async def test_kanban_wake_during_an_admitted_turn_queues_without_interrupting(m
await asyncio.wait_for(deliver_wake(adapter, text=wake, source=source), 10) # accepted, no raise
assert interrupts == [], 'the internal wake interrupted the admitted user turn'
finish.set()
- async with asyncio.timeout(10):
- while wake not in executed:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: wake in executed, what='the wake turn to run')
owner = runner.session_store.peek_session_id(key)
def rows():
return list_session_admissions(authority.db, session_id=owner, pending_only=False)
- async with asyncio.timeout(10):
- while [r['status'] for r in rows()] != ['terminal', 'terminal']:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: [r['status'] for r in rows()] == ['terminal', 'terminal'],
+ what='both admissions to settle')
# The wake ran as its own FIFO turn after the user's, never inside or instead of it.
assert [(r['principal_id'].split(':')[0], r['outcome']) for r in rows()] == [
('messaging', 'completed'), ('automation', 'completed')]
@@ -125,9 +124,8 @@ async def test_idle_loop_tick_runs_as_a_fifo_turn_not_beside_it(monkeypatch):
def rows():
owner = runner.session_store.peek_session_id(key)
return list_session_admissions(authority.db, session_id=owner, pending_only=False) if owner else []
- async with asyncio.timeout(10):
- while [r['status'] for r in rows()] != ['terminal'] or runner._is_session_running(key):
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: [r['status'] for r in rows()] == ['terminal'] and not runner._is_session_running(key),
+ what='the first turn to settle and release the session')
owner = runner.session_store.peek_session_id(key)
class Loop:
@@ -149,10 +147,7 @@ async def test_idle_loop_tick_runs_as_a_fifo_turn_not_beside_it(monkeypatch):
route = {'platform': 'discord', 'chat_id': '42', 'chat_type': 'dm', 'user_id': '42'}
await runner._loop_wakeup_fire_one(owner, SimpleNamespace(awaiting_response=False, next_due_at=0, route=route),
1e12, set())
- async with asyncio.timeout(10):
- while len(started) < 2:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: len(started) >= 2, what='the loop tick turn to start')
assert started == [('hello', True), ('loop tick prompt', True)], 'the tick ran outside the FIFO'
- async with asyncio.timeout(10):
- while [r['status'] for r in rows()] != ['terminal', 'terminal']:
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: [r['status'] for r in rows()] == ['terminal', 'terminal'],
+ what='both admissions to settle')
diff --git a/tests/gateway/test_managed_turn_shutdown_drain.py b/tests/gateway/test_managed_turn_shutdown_drain.py
index 9e516e70b68..4756fa5e1ec 100644
--- a/tests/gateway/test_managed_turn_shutdown_drain.py
+++ b/tests/gateway/test_managed_turn_shutdown_drain.py
@@ -12,6 +12,7 @@ import pytest
from gateway.session_contract import SessionRef
from tests.gateway.restart_test_helpers import make_restart_runner
+from tests.waiting import async_wait_until
@pytest.mark.platforms("linux")
@@ -59,9 +60,8 @@ def test_settlement_stops_a_silent_managed_worker_instead_of_waiting_unbounded(m
async def scenario():
live.task = asyncio.create_task(managed.execute_managed(authority, ref, row, policy=None))
- async with asyncio.timeout(10):
- while 's' not in getattr(authority, '_managed_workers', {}):
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: 's' in getattr(authority, '_managed_workers', {}),
+ what='the managed worker to register')
async with asyncio.timeout(15):
await run_runtime.settle_gateway_runtime(runner)
return live.task
diff --git a/tests/gateway/test_managed_worker_frozen_config.py b/tests/gateway/test_managed_worker_frozen_config.py
index d028694a39f..92076093c07 100644
--- a/tests/gateway/test_managed_worker_frozen_config.py
+++ b/tests/gateway/test_managed_worker_frozen_config.py
@@ -19,6 +19,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
PEER = '''import json, sys
for line in sys.stdin:
@@ -94,9 +95,8 @@ def test_existing_session_keeps_frozen_mcp_transport_after_profile_edit(tmp_path
before = len(peer.requests)
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text='HELLO')
assert 'result' in submitted, submitted
- async with asyncio.timeout(120):
- while status(request_id) != [('terminal',)]:
- await asyncio.sleep(.05)
+ await async_wait_until(lambda: status(request_id) == [('terminal',)], timeout=120, interval=.05,
+ what=f'{request_id} to settle')
tools = json.dumps([r.get('tools') for r in peer.requests[before:]])
return [tag for tag in ('echo_FROZEN_A', 'echo_LIVE_B') if tag in tools]
diff --git a/tests/gateway/test_managed_worker_turn_flags.py b/tests/gateway/test_managed_worker_turn_flags.py
index 764f76d655b..8155db0b004 100644
--- a/tests/gateway/test_managed_worker_turn_flags.py
+++ b/tests/gateway/test_managed_worker_turn_flags.py
@@ -8,10 +8,12 @@ import os
from pathlib import Path
import sqlite3
import threading
+import time
import pytest
from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+from tests.waiting import async_wait_until
class Model(BaseHTTPRequestHandler):
@@ -73,17 +75,19 @@ def _run(tmp_path, scenario):
target.mkdir(exist_ok=True)
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text='DELETE', **flags)
assert 'result' in submitted, submitted
- async with asyncio.timeout(90):
- while status(request_id) != [('terminal',)]:
- snapshot = await rpc(ws, 'session.resume', session_id=sid)
- prompt = next((p for p in snapshot['result']['prompts'] if p['kind'] == 'approval'), None)
- if prompt:
- await rpc(ws, 'approval.respond', session_id=sid, prompt_id=prompt['prompt_id'],
- execution_generation=prompt['execution_generation'], choice='deny')
- while status(request_id) != [('terminal',)]:
- await asyncio.sleep(.05)
- return 'prompted'
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 90
+ while status(request_id) != [('terminal',)]:
+ assert time.monotonic() < deadline, f'{request_id} neither settled nor parked an approval'
+ snapshot = await rpc(ws, 'session.resume', session_id=sid)
+ prompt = next((p for p in snapshot['result']['prompts'] if p['kind'] == 'approval'), None)
+ if prompt:
+ await rpc(ws, 'approval.respond', session_id=sid, prompt_id=prompt['prompt_id'],
+ execution_generation=prompt['execution_generation'], choice='deny')
+ await async_wait_until(lambda: status(request_id) == [('terminal',)],
+ timeout=max(deadline - time.monotonic(), 1), interval=.05,
+ what=f'denied {request_id} to settle')
+ return 'prompted'
+ await asyncio.sleep(.1)
return 'settled'
async def exercise(desc):
diff --git a/tests/gateway/test_msgraph_authority.py b/tests/gateway/test_msgraph_authority.py
index 81beb22b4bb..26ceac65767 100644
--- a/tests/gateway/test_msgraph_authority.py
+++ b/tests/gateway/test_msgraph_authority.py
@@ -23,6 +23,7 @@ async def probe(peer):
from gateway.session_authority import initialize_session_authority
from gateway.session_envelope import restore_native
from hermes_state_runtime import list_session_admissions
+ from tests.waiting import async_wait_until
runner = GatewayRunner()
authority = await initialize_session_authority(runner, profile_id='default', instance_id='graph-test')
adapter = MSGraphWebhookAdapter(PlatformConfig(enabled=True, extra={
@@ -60,9 +61,8 @@ async def probe(peer):
duplicate = await client.post(url, json={'value': [notification]})
assert duplicate.status == 202 and len(rows()) == 1
peer.release.set()
- async with asyncio.timeout(25):
- while rows()[0]['status'] != 'terminal':
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: rows()[0]['status'] == 'terminal', timeout=25,
+ what='the Graph notification turn to settle')
assert len(peer.requests) == 1
# A plugin scheduler owns this route exclusively; do not also infer.
calls = []
diff --git a/tests/gateway/test_parked_profile_served_set.py b/tests/gateway/test_parked_profile_served_set.py
index a6925ad5b6c..bbbe3f449b0 100644
--- a/tests/gateway/test_parked_profile_served_set.py
+++ b/tests/gateway/test_parked_profile_served_set.py
@@ -12,13 +12,14 @@ from gateway.runtime_bootstrap import TicketStore
from gateway.session_authorities import SessionAuthorities
from gateway.session_contract import Submission
from tests.gateway.test_profile_retire_stops_turns import ACTOR, REF, _Agent, _authority
+from tests.waiting import async_wait_until
@pytest.mark.asyncio
async def test_still_retiring_profile_leaves_the_served_set(tmp_path, monkeypatch):
from gateway import session_finite
agent = _Agent(honours_stop=False)
- db, authority, execute, _returned = _authority(tmp_path, agent)
+ db, authority, execute, returned = _authority(tmp_path, agent)
monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
monkeypatch.setattr('gateway.session_cron.unbind_owner', lambda authority: None)
launch = SimpleNamespace(profile_id=str(tmp_path / 'launch'), retiring=False)
@@ -40,5 +41,8 @@ async def test_still_retiring_profile_leaves_the_served_set(tmp_path, monkeypatc
runner.session_ticket_store.mint(profile_id='owned', subject='u', purpose='interactive')
finally:
agent.release.set()
- await asyncio.sleep(.05)
+ # The turn thread returns, then its session task settles; only then may the store close.
+ assert await asyncio.to_thread(returned.wait, 10), 'released turn thread never returned'
+ task = authority.sessions['s'].task
+ await async_wait_until(lambda: task is None or task.done(), what='the released turn to settle')
db.close()
diff --git a/tests/gateway/test_session_cron.py b/tests/gateway/test_session_cron.py
index 87cd45d17b7..52fac15e937 100644
--- a/tests/gateway/test_session_cron.py
+++ b/tests/gateway/test_session_cron.py
@@ -161,6 +161,16 @@ def test_draining_owner_still_answers_status_and_cancel_of_admitted_cron_work(tm
runner.session_authority = authority
admitted = threading.Event()
monkeypatch.setattr(authority, '_schedule', lambda ref: admitted.set())
+ polled_while_draining = threading.Event()
+ real_operation = session_cron.operation
+
+ async def observed_operation(owner, name, params, actor=None):
+ draining = runner._draining
+ result = await real_operation(owner, name, params, actor)
+ if name == 'status' and draining:
+ polled_while_draining.set() # answered, not refused, during the drain
+ return result
+ monkeypatch.setattr(session_cron, 'operation', observed_operation)
async def probe():
session_cron.bind_owner(authority)
@@ -172,7 +182,8 @@ def test_draining_owner_still_answers_status_and_cancel_of_admitted_cron_work(tm
row = claim_session_input(db, epoch=authority.epoch, session_id=sid)
assert await session_cron.operation(
authority, 'cancel', {'session_id': sid, 'admission_id': row['admission_id']}) == {'ok': True}
- await asyncio.sleep(0.3) # the firer polls status at least once during the drain
+ # the firer polls status at least once during the drain, and is answered
+ assert await asyncio.to_thread(polled_while_draining.wait, 10), 'firer never polled status during the drain'
settle_session_input(db, epoch=authority.epoch, admission_id=row['admission_id'],
generation=row['generation'], outcome='completed',
result={'result': {'cron_result': [True, 'doc', 'answer', None]}, 'usage': {}})
diff --git a/tests/gateway/test_session_hosted_daemon.py b/tests/gateway/test_session_hosted_daemon.py
index a218501c99b..7fb8d5b4e6d 100644
--- a/tests/gateway/test_session_hosted_daemon.py
+++ b/tests/gateway/test_session_hosted_daemon.py
@@ -4,6 +4,7 @@ import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import threading
+import time
from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
@@ -85,12 +86,13 @@ def test_native_room_service_local_member_and_restart(tmp_path):
sent = await rpc(ws, 'groups.send', room_id='owned', event_id='input-one',
payload={'text': 'LOCAL_HOSTED_PROOF', 'thread_id': 'thread', 'attachments': saved['manifest']})
assert sent['result']['accepted'], sent
- async with asyncio.timeout(45):
- while True:
- log = await rpc(ws, 'groups.log', room_id='owned')
- if sum(e['kind'] == 'turn.settled' for e in log['result']['events']) >= 2:
- break
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 45
+ while True:
+ log = await rpc(ws, 'groups.log', room_id='owned')
+ if sum(e['kind'] == 'turn.settled' for e in log['result']['events']) >= 2:
+ break
+ assert time.monotonic() < deadline, f'two turns never settled: {log}'
+ await asyncio.sleep(.1)
state = await rpc(ws, 'groups.state', room_id='owned')
assert state['result']['driver_status']['counts'].get('settled') == 2, state
assert len(model.requests) == 2, model.requests
@@ -170,17 +172,18 @@ def test_room_unknown_discard_releases_only_its_followers(tmp_path):
# The killed owner's room lease is same-gateway with a fresh process
# generation, so the restarted owner cannot steal it and waits out the
# 30s TTL (acquire_lease -> LeaseHeldError until expiry). Measured 30.2s.
- async with asyncio.timeout(90):
- while True:
- snapshot = await state(ws)
- actions = [a for a in snapshot['pending_actions'] if a['kind'] == 'discard']
- if actions:
- import sqlite3
- with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
- lease = db.execute('SELECT process_generation FROM hosted_room_driver_leases WHERE room_id=?', ('unknown',)).fetchone()
- if lease is not None and lease[0] != previous['lease']:
- break
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 90
+ while True:
+ snapshot = await state(ws)
+ actions = [a for a in snapshot['pending_actions'] if a['kind'] == 'discard']
+ if actions:
+ import sqlite3
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ lease = db.execute('SELECT process_generation FROM hosted_room_driver_leases WHERE room_id=?', ('unknown',)).fetchone()
+ if lease is not None and lease[0] != previous['lease']:
+ break
+ assert time.monotonic() < deadline, f'restarted owner never took the lease and offered discard: {snapshot}'
+ await asyncio.sleep(.1)
assert len(model.requests) == 1, model.requests
control = {k: v for k, v in actions[0].items() if k != 'kind'}
for method, params, reason in [
@@ -194,12 +197,13 @@ def test_room_unknown_discard_releases_only_its_followers(tmp_path):
assert reply.get('result', {}).get('discarded'), reply
same = await rpc(ws, 'groups.discard', room_id='unknown', **control)
assert same == reply, (same, reply)
- async with asyncio.timeout(30):
- while True:
- snapshot = await state(ws)
- if snapshot['counts'].get('settled', 0) >= 2:
- break
- await asyncio.sleep(.1)
+ deadline = time.monotonic() + 30
+ while True:
+ snapshot = await state(ws)
+ if snapshot['counts'].get('settled', 0) >= 2:
+ break
+ assert time.monotonic() < deadline, f'the follower never settled after discard: {snapshot}'
+ await asyncio.sleep(.1)
assert snapshot['counts'].get('cancelled') == 1, snapshot
assert len(model.requests) == 3, model.requests
try:
diff --git a/tests/gateway/test_session_policy_verbs.py b/tests/gateway/test_session_policy_verbs.py
index ef2a174dacb..e0c3e0fc798 100644
--- a/tests/gateway/test_session_policy_verbs.py
+++ b/tests/gateway/test_session_policy_verbs.py
@@ -9,6 +9,8 @@ from types import SimpleNamespace
import pytest
+from tests.waiting import async_wait_until
+
def _owner(tmp_path, monkeypatch, handle):
from gateway import run
@@ -94,9 +96,8 @@ async def test_move_to_project_rehomes_the_policy_and_row_and_refuses_mid_turn(t
assert busy['error']['data']['reason'] == 'session_busy', busy
assert db.get_session(ref.session_id)['cwd'] == str(tmp_path / 'project-a')
release.set()
- async with asyncio.timeout(10):
- while rt.get_session_admission(db, admission_id=queued.admission_id)['status'] != 'terminal':
- await asyncio.sleep(0.02)
+ await async_wait_until(lambda: rt.get_session_admission(db, admission_id=queued.admission_id)['status'] == 'terminal',
+ what='turn-1 to settle')
moved = await owner.dispatch(_mutation(db, ref, 'mv', 'workspace', {'cwd': str(target)}))
assert moved['result']['cwd'] == str(target), moved
policy = local_receipt(db, ref.session_id)['policy']
@@ -107,9 +108,8 @@ async def test_move_to_project_rehomes_the_policy_and_row_and_refuses_mid_turn(t
started.clear()
second = await authority.submit(owner.actor, Submission('turn-2', ref, {'text': 'two'}, 'queue'))
await asyncio.wait_for(started.wait(), 10)
- async with asyncio.timeout(10):
- while rt.get_session_admission(db, admission_id=second.admission_id)['status'] != 'terminal':
- await asyncio.sleep(0.02)
+ await async_wait_until(lambda: rt.get_session_admission(db, admission_id=second.admission_id)['status'] == 'terminal',
+ what='turn-2 to settle')
assert seen == [str(tmp_path / 'project-a'), str(target)]
missing = await owner.dispatch(_mutation(db, ref, 'mv-missing', 'workspace', {'cwd': str(tmp_path / 'nope')}))
assert missing['error']['data']['reason'] == 'invalid_params'
diff --git a/tests/gateway/test_used_delete_restart.py b/tests/gateway/test_used_delete_restart.py
index 45541d9925e..ece8ec824f3 100644
--- a/tests/gateway/test_used_delete_restart.py
+++ b/tests/gateway/test_used_delete_restart.py
@@ -13,6 +13,7 @@ import httpx
import pytest
from tests.gateway.fixtures.local_recovery_probe import daemon, Model, websocket, rpc
from tests.gateway.test_native_http_auth import ticket, headers as native_headers
+from tests.waiting import async_wait_until
@pytest.mark.platforms("linux")
@@ -55,13 +56,11 @@ def test_used_api_and_native_delete_restart_exact_retry(tmp_path):
sid = created['result']['session_id']
submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='native-once', text='NATIVE_USED_ONCE')
assert submitted['result']['status'] == 'queued', submitted
- async with asyncio.timeout(30):
- while True:
- with sqlite3.connect(home / 'state.db') as db:
- row = db.execute("SELECT status FROM session_admissions WHERE request_id='native-once'").fetchone()
- if row and row[0] == 'terminal':
- break
- await asyncio.sleep(.03)
+ def settled():
+ with sqlite3.connect(home / 'state.db') as db:
+ row = db.execute("SELECT status FROM session_admissions WHERE request_id='native-once'").fetchone()
+ return bool(row and row[0] == 'terminal')
+ await async_wait_until(settled, timeout=30, interval=.03, what='the native turn to settle')
# Wait for the drain's publication, not only the earlier DB terminal commit.
async with asyncio.timeout(20):
while True: