Skip to content

The agent that grows with you

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

Teknium14645d764a70
diff --git a/tests/gateway/test_follower_marker_handoff.py b/tests/gateway/test_follower_marker_handoff.py
index 64bd6aaaa68..994b917bb5a 100644
--- a/tests/gateway/test_follower_marker_handoff.py
+++ b/tests/gateway/test_follower_marker_handoff.py
@@ -5,6 +5,8 @@ from types import SimpleNamespace
import pytest
+from tests.waiting import async_wait_until
+
@pytest.mark.asyncio
async def test_follower_is_claimed_only_after_the_settled_turn_released_its_adopted_marker(tmp_path, monkeypatch):
@@ -51,7 +53,7 @@ async def test_follower_is_claimed_only_after_the_settled_turn_released_its_adop
# (auto-TTS, ledger write) release the adopted marker.
event._turn_marker_handoff = True
reply = await admit_message(authority, event)
- await asyncio.sleep(0.3)
+ await asyncio.sleep(0.3) # health: allow HX013 -- the auto-TTS/ledger window in which the follower must NOT be claimed
await BasePlatformAdapter._release_turn_marker(adapter, event)
return reply
@@ -61,7 +63,7 @@ async def test_follower_is_claimed_only_after_the_settled_turn_released_its_adop
follower_queued.set()
assert await asyncio.wait_for(first, 10) == 'reply to one'
from hermes_state_runtime import get_session_admission
- async with asyncio.timeout(10):
- while get_session_admission(authority.db, admission_id=follower.admission_id)['status'] != 'terminal':
- await asyncio.sleep(0.02)
+ await async_wait_until(
+ lambda: get_session_admission(authority.db, admission_id=follower.admission_id)['status'] == 'terminal',
+ timeout=10, what='the follower to settle')
assert slot_at_follower == [None], "the follower's marker overwrote turn one's before its reply was ledgered"
diff --git a/tests/gateway/test_managed_worker_late_stop.py b/tests/gateway/test_managed_worker_late_stop.py
index 5a0e2b9ff63..06689efa2a9 100644
--- a/tests/gateway/test_managed_worker_late_stop.py
+++ b/tests/gateway/test_managed_worker_late_stop.py
@@ -40,7 +40,7 @@ def _run(mode, supervise):
async with asyncio.timeout(15):
assert await worker.next_frame(HELLO_SECONDS, ack=0) == {'type': 'hello'}
worker.writer.start()
- await asyncio.sleep(ACK + 0.4) # the turn outlives the ack interval before any Stop
+ await asyncio.sleep(ACK + 0.4) # health: allow HX013 -- elapsed time IS the subject: the turn must outlive the ack interval before the first Stop
return await supervise(worker)
try:
diff --git a/tests/gateway/test_native_http_auth.py b/tests/gateway/test_native_http_auth.py
index fcdc75e1abf..a4b13f22639 100644
--- a/tests/gateway/test_native_http_auth.py
+++ b/tests/gateway/test_native_http_auth.py
@@ -142,7 +142,7 @@ def test_native_http_grants_are_single_use_and_bound_to_daemon(tmp_path):
assert client.get('/api/config', params={'ticket': query_ticket}).status_code == 401
assert client.get('/api/config', headers={'Cookie': 'X-Hermes-Gateway-Ticket=' + query_ticket}).status_code == 401
expired = ticket(home, descriptor)
- time.sleep(31) # Real production TTL, not a patched clock or shortened grant.
+ time.sleep(31) # health: allow HX013 -- the real 30 s production ticket TTL must elapse (no patched clock or shortened grant)
assert client.get('/api/config', headers=headers(expired)).status_code == 401
stale = ticket(home, descriptor)
old_instance = descriptor['instance_id']
diff --git a/tests/gateway/test_normal_runtime_boot.py b/tests/gateway/test_normal_runtime_boot.py
index c09c51f9baa..2ed01020d8d 100644
--- a/tests/gateway/test_normal_runtime_boot.py
+++ b/tests/gateway/test_normal_runtime_boot.py
@@ -80,25 +80,27 @@ async def handshake(home, descriptor):
fresh = control(home, 'session-ticket', binding)
async with connect(url, subprotocols=['hermes-gateway-v1',
'hermes-gateway-ticket.' + fresh['ticket']]) as viewer:
- async with asyncio.timeout(25):
- while True:
- snapshot = await rpc(viewer, 'session.resume', session_id=sid)
- if 'LOCAL_ACK_WS_SHARED' in json.dumps(snapshot.get('messages', [])):
- break
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 25
+ while True:
+ snapshot = await rpc(viewer, 'session.resume', session_id=sid)
+ if 'LOCAL_ACK_WS_SHARED' in json.dumps(snapshot.get('messages', [])):
+ break
+ assert time.monotonic() < deadline, snapshot
+ await asyncio.sleep(.05)
assert snapshot['stored_session_id'] == sid
# Transcript persistence precedes terminal publication; await the actual
# replay receipt rather than assuming a persisted reply means settlement.
- async with asyncio.timeout(25):
- while True:
- replay = await rpc(viewer, 'session.events.since', session_id=sid,
- replay_epoch=initial['replay_epoch'],
- last_sequence=initial['last_sequence'])
- assert not replay['snapshot_required'], replay
- completed = [event for event in replay['events'] if event['type'] == 'message.complete']
- if completed:
- break
- await asyncio.sleep(.05)
+ deadline = time.monotonic() + 25
+ while True:
+ replay = await rpc(viewer, 'session.events.since', session_id=sid,
+ replay_epoch=initial['replay_epoch'],
+ last_sequence=initial['last_sequence'])
+ assert not replay['snapshot_required'], replay
+ completed = [event for event in replay['events'] if event['type'] == 'message.complete']
+ if completed:
+ break
+ assert time.monotonic() < deadline, replay
+ await asyncio.sleep(.05)
assert len(completed) == 1, replay
assert 'LOCAL_ACK_WS_SHARED' in completed[0]['payload']['text'], replay
snapshot = await rpc(viewer, 'session.resume', session_id=sid)
diff --git a/tests/gateway/test_session_mutation_compress_preview.py b/tests/gateway/test_session_mutation_compress_preview.py
index 72506ef8e45..cef45d522b9 100644
--- a/tests/gateway/test_session_mutation_compress_preview.py
+++ b/tests/gateway/test_session_mutation_compress_preview.py
@@ -169,7 +169,7 @@ async def test_input_is_admitted_while_compress_summarizes_but_not_claimed_until
'during', ref, {'text': 'typed while compressing'}, 'queue')), 2)
assert receipt.status == 'queued'
claim = asyncio.create_task(authority._claim_next(ref, authority.sessions[ref.session_id]))
- await asyncio.sleep(0.2)
+ await asyncio.sleep(0.2) # health: allow HX013 -- proves the claim does NOT complete while compress holds the gate
assert not claim.done(), 'a turn was claimed under a compression still preparing its transcript'
release.set()
reply = await asyncio.wait_for(compressing, 10)
diff --git a/tests/gateway/test_settlement_lock_liveness.py b/tests/gateway/test_settlement_lock_liveness.py
index 1f9543fc32e..71aaff52830 100644
--- a/tests/gateway/test_settlement_lock_liveness.py
+++ b/tests/gateway/test_settlement_lock_liveness.py
@@ -6,14 +6,15 @@ publication keep running; the commit still looks atomic with its completion fram
import asyncio
import sqlite3
import threading
-import time
-
import pytest
from gateway.session_contract import Principal, Submission
from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit
+from tests.waiting import async_wait_until
-_HOLD_S = 1.5
+# The competing writer holds the lock until the test has watched the loop run (``go``); this is
+# only the ceiling after which a stalled loop gets it back and the test fails instead of hanging.
+_HOLD_CEILING_S = 30.0
VIEWER = Principal('human', 'owned', frozenset({'session:read', 'session:submit'}), 'viewer')
@@ -22,7 +23,7 @@ async def _settling_behind_a_held_writer(tmp_path, monkeypatch):
from gateway import session_results
db, authority = _authority(tmp_path, monkeypatch)
monkeypatch.setattr(authority, '_schedule', lambda ref: None)
- frames, entered, released = [], threading.Event(), threading.Event()
+ frames, entered, released, go = [], threading.Event(), threading.Event(), threading.Event()
authority.sessions['s'].event_stream.observers.add(frames.append)
settle = session_results.settle_session_input
@@ -38,7 +39,7 @@ async def _settling_behind_a_held_writer(tmp_path, monkeypatch):
writer.execute('BEGIN IMMEDIATE')
def release():
- time.sleep(_HOLD_S)
+ go.wait(_HOLD_CEILING_S)
released.set()
writer.rollback()
writer.close()
@@ -47,9 +48,8 @@ async def _settling_behind_a_held_writer(tmp_path, monkeypatch):
monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
await authority.submit(ACTOR, Submission('work', REF, {'text': 'work'}, 'queue'))
drain = asyncio.create_task(authority._drain(REF))
- while not entered.is_set():
- await asyncio.sleep(0.01)
- return db, authority, frames, released, drain
+ await async_wait_until(entered.is_set, what='the settlement to reach the held writer')
+ return db, authority, frames, released, go, drain
def _types(frames):
@@ -58,13 +58,16 @@ def _types(frames):
@pytest.mark.asyncio
async def test_attach_during_a_contended_settlement_leaves_the_loop_free(tmp_path, monkeypatch):
- db, authority, frames, released, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
+ db, authority, frames, released, go, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
with db:
ticks = []
asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))
attach = asyncio.create_task(authority.attach(VIEWER, REF))
- await asyncio.sleep(0.3)
- assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ try:
+ await async_wait_until(lambda: ticks, timeout=_HOLD_CEILING_S + 5, what='the 50 ms callback')
+ assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ finally:
+ go.set()
snapshot = await asyncio.wait_for(attach, 10)
await asyncio.wait_for(drain, 10)
# The snapshot still never shows the terminal row without its completion frame.
@@ -78,15 +81,18 @@ async def test_attach_during_a_contended_settlement_leaves_the_loop_free(tmp_pat
@pytest.mark.asyncio
async def test_pending_publication_during_a_contended_settlement_keeps_idle_after_completion(
tmp_path, monkeypatch):
- db, authority, frames, released, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
+ db, authority, frames, released, go, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
with db:
ticks = []
loop = asyncio.get_running_loop()
# A loop-side publisher (submit/cancel/automation call this) racing the settlement.
loop.call_later(0.02, authority._publish_pending, REF)
loop.call_later(0.05, lambda: ticks.append(released.is_set()))
- await asyncio.sleep(0.3)
- assert ticks == [False], 'pending publication waited for the held writer'
+ try:
+ await async_wait_until(lambda: ticks, timeout=_HOLD_CEILING_S + 5, what='the 50 ms callback')
+ assert ticks == [False], 'pending publication waited for the held writer'
+ finally:
+ go.set()
await asyncio.wait_for(drain, 10)
kinds = _types(frames)
start, complete = kinds.index(('message.start', None)), kinds.index(('message.complete', None))
@@ -103,48 +109,46 @@ async def test_cancel_behind_a_held_writer_leaves_the_loop_free_and_still_settle
with db:
receipt = await authority.submit(ACTOR, Submission('queued', REF, {'text': 'queued'}, 'queue'))
waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())
- released = threading.Event()
- writer = sqlite3.connect(str(tmp_path / 'state.db'), isolation_level=None, check_same_thread=False)
- writer.execute('BEGIN IMMEDIATE')
-
- def release():
- time.sleep(_HOLD_S)
- released.set()
- writer.rollback()
- writer.close()
- threading.Thread(target=release, daemon=True).start()
+ released, go = _hold_writer(tmp_path)
ticks = []
asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))
cancel = asyncio.create_task(authority.cancel_queued(ACTOR, REF, receipt.admission_id))
- await asyncio.sleep(0.3)
- assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ try:
+ await async_wait_until(lambda: ticks, timeout=_HOLD_CEILING_S + 5, what='the 50 ms callback')
+ assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ finally:
+ go.set()
cancelled = await asyncio.wait_for(cancel, 10)
assert (cancelled.status, cancelled.outcome) == ('terminal', 'cancelled')
assert waiter.done() and receipt.admission_id not in authority.cancel_obligations
def _hold_writer(tmp_path):
- """A second connection holds the state.db write lock for ``_HOLD_S`` (another process)."""
- released = threading.Event()
+ """A second connection holds the state.db write lock (another process) until ``go`` is set,
+ or ``_HOLD_CEILING_S`` passes; ``released`` is set just before it lets go."""
+ released, go = threading.Event(), threading.Event()
writer = sqlite3.connect(str(tmp_path / 'state.db'), isolation_level=None, check_same_thread=False)
writer.execute('BEGIN IMMEDIATE')
def release():
- time.sleep(_HOLD_S)
+ go.wait(_HOLD_CEILING_S)
released.set()
writer.rollback()
writer.close()
threading.Thread(target=release, daemon=True).start()
- return released
+ return released, go
async def _loop_stays_free(tmp_path, operation):
- released = _hold_writer(tmp_path)
+ released, go = _hold_writer(tmp_path)
ticks = []
asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))
task = asyncio.create_task(operation())
- await asyncio.sleep(0.3)
- assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ try:
+ await async_wait_until(lambda: ticks, timeout=_HOLD_CEILING_S + 5, what='the 50 ms callback')
+ assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ finally:
+ go.set()
return await asyncio.wait_for(task, 10)
@@ -244,8 +248,7 @@ async def test_admission_schedules_its_drain_in_the_admitting_callers_step(tmp_p
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
- while mutation_tasks(authority):
- await asyncio.sleep(0.01)
+ await async_wait_until(lambda: not mutation_tasks(authority), timeout=5, what='the mid-commit write to finish')
# The commit's done-callback schedules the drain, and the drain task runs a step after
# that: wait for the observable, not for one particular tick.
async with asyncio.timeout(5):
diff --git a/tests/gateway/test_webhook_authority.py b/tests/gateway/test_webhook_authority.py
index a13bf31e55b..bc9bd1eb61f 100644
--- a/tests/gateway/test_webhook_authority.py
+++ b/tests/gateway/test_webhook_authority.py
@@ -23,6 +23,7 @@ async def probe(peer):
from gateway.run import GatewayRunner
from gateway.session_authority import initialize_session_authority
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='webhook-test')
@@ -58,17 +59,15 @@ async def probe(peer):
assert duplicate.status in (200, 202), await duplicate.text()
assert 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 webhook admission to settle')
# Lose the process-local optimization: durable identity still suppresses replay.
adapter._seen_deliveries.clear()
duplicate = await client.post(url, data=body, headers=headers)
assert duplicate.status in (200, 202), await duplicate.text()
assert len(rows()) == 1 and len(peer.requests) == 1
- async with asyncio.timeout(5):
- while adapter._background_tasks:
- await asyncio.sleep(.01)
+ await async_wait_until(lambda: not adapter._background_tasks, timeout=5,
+ what='the webhook background tasks to finish')
assert authority.db.get_session(rows()[0]['target_session_id'])['ended_at'] is not None
Path(os.environ['HERMES_HOME'], 'webhook-receipt.json').write_text(json.dumps({
'failed_status': failed.status, 'retry_status': accepted.status,
diff --git a/tests/hermes_cli/test_gateway_client_rpc.py b/tests/hermes_cli/test_gateway_client_rpc.py
index bbe6c5b781d..1ed2dfa3da0 100644
--- a/tests/hermes_cli/test_gateway_client_rpc.py
+++ b/tests/hermes_cli/test_gateway_client_rpc.py
@@ -63,7 +63,7 @@ async def test_compress_waits_past_the_default_rpc_budget(monkeypatch):
return {'id': req['id'], 'result': {'revision': 1, 'execution_generation': 1}}
async def commit(): # a 120 s summary (scaled) then the receipt
- await asyncio.sleep(0.12)
+ await asyncio.sleep(0.12) # health: allow HX013 -- the reply must land after the scaled 30 ms default budget expired
await owner.inbox.put(json.dumps({'id': req['id'], 'result': {'status': 'applied'}}))
asyncio.ensure_future(commit())
diff --git a/tests/tools/test_clarify_gateway.py b/tests/tools/test_clarify_gateway.py
index 1a038fc304c..31b409f123d 100644
--- a/tests/tools/test_clarify_gateway.py
+++ b/tests/tools/test_clarify_gateway.py
@@ -12,6 +12,8 @@ import threading
import time
from concurrent.futures import ThreadPoolExecutor
+from tests.waiting import wait_until
+
def _clear_clarify_state():
"""Reset module-level state between tests."""
@@ -281,8 +283,7 @@ class TestUnlimitedWait:
t = threading.Thread(target=waiter, daemon=True) # a regression must fail, not hang exit
t.start()
- while "tid" not in box:
- time.sleep(0.01)
+ wait_until(lambda: "tid" in box, timeout=5, what="the waiter thread to start")
try:
set_interrupt(True, box["tid"], reason="gateway shutdown")
t.join(timeout=5.0)