The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: synchronize nonblocking and teardown assertions
ethernetc4cad9c89db6
diff --git a/tests/cron/test_misfire_catchup.py b/tests/cron/test_misfire_catchup.pyindex 53ceb31887b..644ac3b1420 100644--- a/tests/cron/test_misfire_catchup.py+++ b/tests/cron/test_misfire_catchup.py@@ -8,7 +8,6 @@ gateway housekeeping, claims and fires those jobs after a grace window."""import threading-import timefrom datetime import timedeltaimport pytest@@ -145,19 +144,30 @@ class TestFireOverdueJobs:assert fire_overdue_jobs(provider2) == 0def test_dispatch_is_nonblocking(self, tmp_cron_dir):- """fire_claimed runs off-thread — a slow job must not stall the- sweep (housekeeping loop) for the length of an agent run."""+ """The sweep returns while the dispatched provider is still blocked."""+ worker_running = threading.Event()+ release = threading.Event()- class SlowProvider(RecordingProvider):+ class BlockedProvider(RecordingProvider):def fire_claimed(self, claimed_job, **kw):- time.sleep(3.0)- return super().fire_claimed(claimed_job, **kw)+ worker_running.set()+ try:+ assert release.wait(timeout=10), "test never released the worker"+ return super().fire_claimed(claimed_job, **kw)+ finally:+ self._done.set()job = create_job(prompt="p", schedule="every 1h")_park_in_past(job["id"], minutes=30)- provider = SlowProvider()- start = time.monotonic()- assert fire_overdue_jobs(provider) == 1- assert time.monotonic() - start < 1.0 # returned before the run+ provider = BlockedProvider()+ try:+ # Must return while the dispatched run is still blocked.+ assert fire_overdue_jobs(provider) == 1+ # The run actually started off-thread (dispatch happened, not a skip).+ assert worker_running.wait(timeout=10)+ assert not provider._done.is_set()+ assert provider.fired == []+ finally:+ release.set()assert provider.wait_fired(timeout=10)assert provider.fired == [job["id"]]diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.pyindex 9853dbc2291..c5254bfc81e 100644--- a/tests/cron/test_parallel_pool.py+++ b/tests/cron/test_parallel_pool.py@@ -6,7 +6,6 @@ prevented the ticker thread from firing, causing all other jobs to be fast-forwaimport concurrent.futuresimport threading-import timefrom unittest.mock import patchimport pytest@@ -231,7 +230,7 @@ class TestSyncMode:sched._shutdown_parallel_pool()def test_sync_false_returns_immediately(self, tmp_path, monkeypatch):- """sync=False returns before parallel jobs finish (optimistic count)."""+ """The ticker returns while its dispatched worker is still blocked."""import cron.scheduler as schedsched._parallel_pool = None@@ -248,10 +247,16 @@ class TestSyncMode:"deliver": "local",}- barrier = threading.Barrier(2, timeout=5)+ worker_started = threading.Event()+ release = threading.Event()+ worker_finished = threading.Event()def slow_run(j, *, defer_agent_teardown=None, **_kw):- barrier.wait() # blocks until test thread also waits+ worker_started.set()+ try:+ assert release.wait(timeout=10), "test never released the worker"+ finally:+ worker_finished.set()return True, "out", "resp", Nonemonkeypatch.setattr(sched, "get_due_jobs", lambda: [job])@@ -261,24 +266,20 @@ class TestSyncMode:monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)- start = time.monotonic()- n = sched.tick(verbose=False, sync=False) # opt-in: non-blocking- elapsed = time.monotonic() - start-- assert n == 1 # optimistic count- assert elapsed < 1.0 # returned immediately, didn't wait for slow_run-- # Let the job finish so cleanup works.- barrier.wait()- time.sleep(0.1)- sched._shutdown_parallel_pool()+ try:+ assert sched.tick(verbose=False, sync=False) == 1+ assert worker_started.wait(timeout=10)+ assert not worker_finished.is_set()+ finally:+ release.set()+ sched._shutdown_parallel_pool()class TestWorkdirParallelPool:"""Task-scoped workdir jobs use the normal persistent parallel pool."""def test_workdir_job_does_not_block_ticker(self, tmp_path, monkeypatch):- """sync=False returns immediately even when a workdir job is slow."""+ """The ticker returns while its dispatched worker is still blocked."""import cron.scheduler as schedsched._parallel_pool = None@@ -296,10 +297,16 @@ class TestWorkdirParallelPool:"workdir": str(tmp_path),}- barrier = threading.Barrier(2, timeout=5)+ worker_started = threading.Event()+ release = threading.Event()+ worker_finished = threading.Event()def slow_run(j, *, defer_agent_teardown=None, **_kw):- barrier.wait()+ worker_started.set()+ try:+ assert release.wait(timeout=10), "test never released the worker"+ finally:+ worker_finished.set()return True, "out", "resp", Nonemonkeypatch.setattr(sched, "get_due_jobs", lambda: [job])@@ -309,16 +316,13 @@ class TestWorkdirParallelPool:monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)- start = time.monotonic()- n = sched.tick(verbose=False, sync=False)- elapsed = time.monotonic() - start-- assert n == 1 # optimistic count- assert elapsed < 1.0 # did NOT block on the slow workdir job-- barrier.wait()- time.sleep(0.1)- sched._shutdown_parallel_pool()+ try:+ assert sched.tick(verbose=False, sync=False) == 1+ assert worker_started.wait(timeout=10)+ assert not worker_finished.is_set()+ finally:+ release.set()+ sched._shutdown_parallel_pool()def test_workdir_running_guard_prevents_double_dispatch(self, tmp_path, monkeypatch):"""A workdir job already in _running_job_ids is skipped on next tick."""diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.pyindex 1bb266b05b5..546dee6d949 100644--- a/tests/gateway/test_session_hygiene.py+++ b/tests/gateway/test_session_hygiene.py@@ -1681,14 +1681,13 @@ async def test_hygiene_does_not_wait_ceiling_after_fence_cancel(if commit_fence is not None:commit_fence.try_cancel_before_commit()worker_started.set()- # Keep the worker alive (and keep reporting "progress") so a- # host that still extends to the 600s ceiling would stall here.- deadline = time.monotonic() + 2.0- while time.monotonic() < deadline:+ # Keep the worker alive (and keep reporting "progress") until the+ # test releases it — which happens only AFTER the host has+ # returned. A host that still extends toward the 600s ceiling+ # would stall here and blow the bounded wait_for below.+ while not release_worker.is_set():if commit_fence is not None:commit_fence.touch_progress()- if release_worker.is_set():- breaktime.sleep(0.02)return (messages, None)@@ -1698,16 +1697,11 @@ async def test_hygiene_does_not_wait_ceiling_after_fence_cancel(runner, adapter, event = _make_cooldown_runner(monkeypatch, tmp_path, HungAfterFenceCancelAgent, db, session_id)- started = time.monotonic()- result = await runner._handle_message(event)- elapsed = time.monotonic() - started+ result = await asyncio.wait_for(runner._handle_message(event), timeout=30)assert result == "ok"- assert worker_started.wait(timeout=2)- assert elapsed < 2.0, (- f"hygiene host waited {elapsed:.1f}s after fence cancel — "- "must not extend toward the 600s ceiling (#96953)"- )+ assert worker_started.wait(timeout=10)+ assert not cleanup_done.is_set()assert runner._run_agent.await_count == 1state = db.get_compression_failure_cooldown(session_id)assert state is not None and state["remaining_seconds"] > 0@@ -1715,8 +1709,10 @@ async def test_hygiene_does_not_wait_ceiling_after_fence_cancel("Context compression timed out" in s["content"] for s in adapter.sent), "fence-cancel is not a summary-model timeout; no timeout toast"release_worker.set()- await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)+ assert await asyncio.to_thread(cleanup_done.wait, 10)finally:+ release_worker.set()+ await asyncio.to_thread(cleanup_done.wait, 10)db.close()@@ -1811,6 +1807,6 @@ async def test_hygiene_unwind_records_cooldown(monkeypatch, tmp_path):f"{state!r}")release_worker.set()- await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)+ assert await asyncio.to_thread(cleanup_done.wait, 10)finally:db.close()diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex b1a21a665d8..5ae4382d454 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -5087,7 +5087,7 @@ def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):def _slow_teardown(_session, *, end_reason="tui_close"):assert end_reason == "ws_orphan_reap"teardown_started.set()- assert release_teardown.wait(timeout=2.0)+ assert release_teardown.wait(timeout=30.0)monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0.01)monkeypatch.setattr(server.threading, "Timer", _Timer)@@ -5102,15 +5102,15 @@ def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):thread.start()acquired = Falsetry:- assert teardown_started.wait(timeout=1.0)+ assert teardown_started.wait(timeout=10.0)assert "slow-orphan" not in server._sessions- acquired = server._session_resume_lock.acquire(timeout=0.2)+ acquired = server._session_resume_lock.acquire(blocking=False)assert acquired, "orphan teardown kept the global resume lock held"finally:if acquired:server._session_resume_lock.release()release_teardown.set()- thread.join(timeout=2.0)+ thread.join(timeout=10.0)server._sessions.pop("slow-orphan", None)assert not thread.is_alive()diff --git a/tests/tools/test_delegate_timeout_cleanup.py b/tests/tools/test_delegate_timeout_cleanup.pyindex 2c16d91e730..62b335acb7b 100644--- a/tests/tools/test_delegate_timeout_cleanup.py+++ b/tests/tools/test_delegate_timeout_cleanup.py@@ -31,11 +31,11 @@ class _SlowUnwindingChild:def run_conversation(self, **_kwargs):self.started.set()- assert self.interrupted.wait(timeout=1)+ assert self.interrupted.wait(timeout=30)# Model the real child turn's finally path: it still performs session# activity/SQLite cleanup after the parent requests interruption.self.unwinding.set()- assert self.allow_finish.wait(timeout=2)+ assert self.allow_finish.wait(timeout=30)self.finished.set()return {"final_response": "",@@ -68,6 +68,17 @@ def test_timeout_does_not_close_child_while_worker_is_unwinding(monkeypatch):monkeypatch.setattr(delegate_tool, "_get_child_timeout", lambda: 0.5)monkeypatch.setattr(delegate_tool, "_get_worktree_isolation", lambda: False)+ from tools.daemon_pool import DaemonThreadPoolExecutor++ submit = DaemonThreadPoolExecutor.submit++ def submit_started(executor, *args, **kwargs):+ future = submit(executor, *args, **kwargs)+ assert child.started.wait(timeout=10)+ return future++ # Timeout accounting starts only after this test's child is running.+ monkeypatch.setattr(DaemonThreadPoolExecutor, "submit", submit_started)result = delegate_tool._run_single_child(task_index=0,goal="exercise timeout teardown",@@ -76,15 +87,15 @@ def test_timeout_does_not_close_child_while_worker_is_unwinding(monkeypatch):)assert result["status"] == "timeout"- assert child.unwinding.wait(timeout=1)+ assert child.unwinding.wait(timeout=10)try:assert not child.closed.is_set(), ("timed-out child.close() ran before its conversation thread unwound")finally:child.allow_finish.set()- assert child.finished.wait(timeout=1)- assert child.closed.wait(timeout=1)+ assert child.finished.wait(timeout=10)+ assert child.closed.wait(timeout=10)assert not child.close_while_running, ("timed-out child.close() raced its still-running conversation thread")