The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(hx013): wait for conditions, not the clock, in acp and gateway fixtures
Tekniumf88d529f97eb
diff --git a/tests/acp_adapter/test_gateway_editor_wire.py b/tests/acp_adapter/test_gateway_editor_wire.pyindex c3a51c95ff4..406a0ab7ee0 100644--- a/tests/acp_adapter/test_gateway_editor_wire.py+++ b/tests/acp_adapter/test_gateway_editor_wire.py@@ -7,6 +7,7 @@ import jsonimport pytestfrom tests.acp_adapter.test_gateway_sessions import editor, viewer+from tests.waiting import async_wait_untilclass EditPeer(BaseHTTPRequestHandler):@@ -82,9 +83,8 @@ async def test_real_editor_diff_requires_native_consent_before_write(daemon, tmptask = asyncio.create_task(acp.rpc('session/prompt', sessionId=sid,prompt=[{'type': 'text', 'text': 'Edit the owned fixture'}]))try:- async with asyncio.timeout(20):- 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=20, what='the edit permission request')permission = next(f for f in acp.frames if f.get('method') == 'session/request_permission')call = permission['params']['toolCall']assert call['kind'] == 'edit', permissiondiff --git a/tests/acp_adapter/test_gateway_unacked_slash.py b/tests/acp_adapter/test_gateway_unacked_slash.pyindex 331af2a8605..dbcbf1d2544 100644--- a/tests/acp_adapter/test_gateway_unacked_slash.py+++ b/tests/acp_adapter/test_gateway_unacked_slash.py@@ -13,6 +13,7 @@ from gateway.session_controls import AuthorityConnectionfrom hermes_cli.gateway_client import GatewayClientErrorfrom hermes_state_runtime import list_session_admissionsfrom tests.acp_adapter.test_gateway_submit_retry import Wire+from tests.waiting import async_wait_untilclass SlashWire(Wire):@@ -57,9 +58,7 @@ async def test_repeated_prompt_after_slash_command_is_new_work(tmp_path, monkeyptry:with pytest.raises(GatewayClientError, match='outcome is unknown'):await agent.prompt([acp.text_block('yes')], s)- async with asyncio.timeout(5):- while 'ACK_yes' not in updates:- await asyncio.sleep(0.01)+ await async_wait_until(lambda: 'ACK_yes' in updates, timeout=5, what='the lost-ack reply update')# Read-only slash work between the lost-ack prompt and the deliberate repeat.await asyncio.wait_for(agent.prompt([acp.text_block('/compress --preview')], s), 5)response = await asyncio.wait_for(agent.prompt([acp.text_block('yes')], s), 5)diff --git a/tests/gateway/fixtures/automation_peer.py b/tests/gateway/fixtures/automation_peer.pyindex 449a156b98c..2e5feeefff6 100644--- a/tests/gateway/fixtures/automation_peer.py+++ b/tests/gateway/fixtures/automation_peer.py@@ -13,6 +13,7 @@ import timeimport websocketsfrom tests.gateway.test_normal_runtime_boot import control+from tests.waiting import async_wait_untilfrom local_recovery_probe import websocket, rpc@@ -103,9 +104,7 @@ async def probe(root, base, mode):return [dict(r) for r in db.execute('SELECT * FROM session_admissions ORDER BY seq')]async def wait_for(predicate, seconds=35):- async with asyncio.timeout(seconds):- while not predicate():- await asyncio.sleep(.03)+ await async_wait_until(predicate, timeout=seconds)proc = Nonetry:diff --git a/tests/gateway/fixtures/local_automation_peer.py b/tests/gateway/fixtures/local_automation_peer.pyindex cdc8c65814f..0c8d81e0456 100644--- a/tests/gateway/fixtures/local_automation_peer.py+++ b/tests/gateway/fixtures/local_automation_peer.py@@ -10,6 +10,7 @@ import threadingfrom automation_peer import Modelfrom local_recovery_probe import daemon, websocket, rpc+from tests.waiting import async_wait_untildef probe(base, source):@@ -41,9 +42,7 @@ def probe(base, source):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)async def run(desc):async with websocket(home, desc) as ws:@@ -67,7 +66,9 @@ def probe(base, source):await submit('follower', 'HUMAN_FIFO_FOLLOWER')# Last observer closes while owner remains in a model call.model.gate.touch()- await asyncio.sleep(8)+ await wait(lambda: any(r['principal_id'].startswith('automation:') for r in rows()))+ # The completion is in; a duplicate admission would land within this window (none may).+ await asyncio.sleep(8) # health: allow HX013 -- proves no second automation row arrivesledger = rows()automatic = [r for r in ledger if r['principal_id'].startswith('automation:')]assert automatic, {'missing_automation': ledger}@@ -119,7 +120,7 @@ def probe(base, source):async def recovered(desc):await wait(lambda: all(r['status'] == 'terminal' for r in rows()))# Leave ordinary startup/watchers running before checking zero replay.- await asyncio.sleep(8)+ await asyncio.sleep(8) # health: allow HX013 -- proves recovery replays nothing in the windowassert len(rows()) == len(receipt['committed']), rows()assert rows()[-1]['outcome'] == 'completed', rows()async with websocket(home, desc) as ws:diff --git a/tests/gateway/fixtures/local_status_notice_peer.py b/tests/gateway/fixtures/local_status_notice_peer.pyindex 1b3a880ee8b..86d5fb66be8 100644--- a/tests/gateway/fixtures/local_status_notice_peer.py+++ b/tests/gateway/fixtures/local_status_notice_peer.py@@ -77,7 +77,6 @@ async def probe():async with asyncio.timeout(30):while not any(f.get('params', {}).get('type') == 'message.complete' for f in frames):frames.append(json.loads(await ws.recv()))- await asyncio.sleep(0.3)events = [f['params'] for f in frames if f.get('method') == 'event']# The classic `hermes chat` view renders what reached it on stderr.import contextlibdiff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.pyindex 0c9ff3c9130..1e5ea197c3b 100644--- a/tests/gateway/test_api_canonical_projection.py+++ b/tests/gateway/test_api_canonical_projection.py@@ -11,6 +11,7 @@ from gateway.platforms import api_server as _api_serverfrom gateway.platforms.api_server_runs import _RunLaunch, _execute_runfrom gateway.session_api_turn import admit_api_turnfrom gateway.session_ingress import execute_admission+from tests.waiting import async_wait_untilPNG = base64.b64encode(b'\x89PNG\r\n\x1a\n' + b'\x00' * 64).decode()@@ -243,9 +244,8 @@ async def test_room_grant_answers_the_clarify_prompt_its_run_raised(api, owner,return entry.responseowner.runner._handle_message = handlerun = asyncio.ensure_future(_execute_run(api, launch, _api_server=_api_server))- async with asyncio.timeout(10):- while not (run_projection(api, 'run_room') or {}).get('pending_controls'):- await asyncio.sleep(0.02)+ await async_wait_until(lambda: (run_projection(api, 'run_room') or {}).get('pending_controls'),+ timeout=10, what='the clarify prompt projected on the run')prompt = run_projection(api, 'run_room')['pending_controls'][0]body = {'request_id': prompt['prompt_id'], 'execution_generation': prompt['execution_generation'], 'answer': 'b'}app = web.Application()diff --git a/tests/gateway/test_bot_paused_waiter.py b/tests/gateway/test_bot_paused_waiter.pyindex 21515eed2d6..8b0961ab333 100644--- a/tests/gateway/test_bot_paused_waiter.py+++ b/tests/gateway/test_bot_paused_waiter.py@@ -4,6 +4,7 @@ import asyncioimport pytestfrom tests.gateway.test_session_bot_retry import KEY+from tests.waiting import async_wait_untilpytest_plugins = ['tests.gateway.test_session_bot_retry']@@ -19,16 +20,18 @@ async def test_paused_bot_follower_rearms_until_its_durable_completion(bot, monkmonkeypatch.setattr(authority, '_schedule', lambda ref: None)await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))authority._pause(SessionRef(authority.profile_id, bot.chat), 'session_busy')- async with asyncio.timeout(5):- while (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] != 'queued':- await asyncio.sleep(.01)+ for _ in range(500): # bounded poll: a slow runner stretches the rounds, never fails early+ if (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] == 'queued':+ break+ await asyncio.sleep(.01)record = (await asyncio.to_thread(read_delivery_result, bot.home, KEY))assert record['status'] == 'queued'schedule(SessionRef(authority.profile_id, bot.chat))await asyncio.wait_for(authority.sessions[bot.chat].task, 5)- async with asyncio.timeout(5):- while (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] != 'settled':- await asyncio.sleep(.01)+ for _ in range(500):+ if (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] == 'settled':+ break+ await asyncio.sleep(.01)record = (await asyncio.to_thread(read_delivery_result, bot.home, KEY))assert record['status'] == 'settled' and record['reply'] == 'pong'@@ -65,15 +68,18 @@ async def test_paused_watcher_never_publishes_final_failed_while_retry_is_due(boholder = asyncio.create_task(hold_mailbox())await held.wait()authority._pause(ref, 'session_busy')- await asyncio.sleep(0.05)+ # Let the pause reach the watcher: it is parked either on its reply future (kept by a+ # session_busy pause) or, if the pause woke it, on the held mailbox lock.+ _key, _task, future = authority._bot_reply_watchers[KEY]+ await async_wait_until(lambda: not future.done() or getattr(authority._bot_mailbox_lock, '_waiters', None),+ timeout=5, what='the watcher parked after the pause')monkeypatch.setattr(authority, '_schedule', schedule)schedule(ref)await asyncio.wait_for(authority.sessions[bot.chat].task, 5)gate.set()await holder- async with asyncio.timeout(5):- while not (len(_admissions(bot)) >= 2 and all(r['status'] == 'terminal' for r in _admissions(bot))):- await asyncio.sleep(.02)+ await async_wait_until(lambda: len(_admissions(bot)) >= 2 and all(r['status'] == 'terminal' for r in _admissions(bot)),+ timeout=5, what='the retried admission settled')for task in list(getattr(authority, '_bot_receipt_tasks', ())):await asyncio.gather(task, return_exceptions=True)assert 'failed' not in written, writtendiff --git a/tests/gateway/test_busy_burst_merge_shared.py b/tests/gateway/test_busy_burst_merge_shared.pyindex 390a3894cd5..8f948b1df2d 100644--- a/tests/gateway/test_busy_burst_merge_shared.py+++ b/tests/gateway/test_busy_burst_merge_shared.py@@ -9,6 +9,8 @@ import asyncioimport pytest+from tests.waiting import async_wait_until+PNG = b'\x89PNG\r\n\x1a\n' + b'\x00' * 24# (case, follow-ups as (sender, text, photo?), expected admitted (text, media count) after 'A')@@ -87,7 +89,5 @@ async def test_busy_burst_is_admitted_once(monkeypatch, tmp_path, case, follow_uassert [(r['payload']['text'], len(r['payload']['native_text_v1'].get('media', [])))for r in rows[1:]] == expectedfinish.set()- async with asyncio.timeout(10):- while len(executed) < 1 + len(expected):- await asyncio.sleep(0.01)+ await async_wait_until(lambda: len(executed) >= 1 + len(expected), timeout=10, what='every merged turn executed')await asyncio.to_thread(authority.db.close)diff --git a/tests/gateway/test_cron_owner_progress_stamp.py b/tests/gateway/test_cron_owner_progress_stamp.pyindex 18c9b461b92..e41762c6cbd 100644--- a/tests/gateway/test_cron_owner_progress_stamp.py+++ b/tests/gateway/test_cron_owner_progress_stamp.py@@ -6,10 +6,10 @@ no execution id at all (its stamper returned early) and the firer never stamped,run was swept ``unknown`` once the derived stale bound passed."""import asyncioimport threading-import timefrom types import SimpleNamespaceimport cron.executions as executions_mod+from tests.waiting import wait_untildef test_owner_progress_reaches_the_firers_ledger_row(tmp_path, monkeypatch):@@ -42,12 +42,17 @@ def test_owner_progress_reaches_the_firers_ledger_row(tmp_path, monkeypatch):admitted = threading.Event()monkeypatch.setattr(authority, '_schedule', lambda ref: admitted.set())+ def firer_stamped():+ with _transaction() as conn:+ return conn.execute('SELECT progress_at FROM executions WHERE id=?', (execution['id'],)).fetchone()[0]+def run_job(job, *, extra_prompt, execution_id, cancel_event):stamper = scheduler_liveness.ExecutionProgressStamper(str(job.get('execution_id') or ''), 'job', idle_seconds=lambda: 0.0, every_seconds=0.001)- time.sleep(0.01)+ stamper._last -= 1 # its stamp cadence has elapsedstamper.tick()- time.sleep(0.6) # the firer polls status while the agent works+ # The agent keeps working until the firer, polling status, has refreshed its own row.+ wait_until(firer_stamped, timeout=20, what="the firer's ledger row stamped with progress")return (True, 'doc', 'answer', None)monkeypatch.setattr(scheduler, 'run_job', run_job)diff --git a/tests/gateway/test_managed_unstarted_cancel.py b/tests/gateway/test_managed_unstarted_cancel.pyindex 7a307634dab..ce722a34096 100644--- a/tests/gateway/test_managed_unstarted_cancel.py+++ b/tests/gateway/test_managed_unstarted_cancel.py@@ -10,6 +10,7 @@ import pytestfrom gateway.session_contract import Submissionfrom hermes_state_runtime import get_session_admissionfrom tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF+from tests.waiting import async_wait_until@pytest.mark.asyncio@@ -55,9 +56,8 @@ async def test_cancel_before_worker_reservation_settles_interrupted(tmp_path, moassert row['status'] == 'terminal' and row['outcome'] == 'interrupted'assert authority.sessions['s'].event_stream.execution == {}if phase != 'environment':- async with asyncio.timeout(10):- while not children or any(child.poll() is None for child in children):- await asyncio.sleep(.01)+ await async_wait_until(lambda: children and all(child.poll() is not None for child in children),+ timeout=10, what='the managed worker child exited')assert db._read_one('SELECT COUNT(*) FROM worker_executions')[0] == 0finally:release.set()