diff --git a/tests/test_pipeline/test_async_fan_out_does_not_hang.py b/tests/test_pipeline/test_async_fan_out_does_not_hang.py index 79f11ea72..c4a0ed6df 100644 --- a/tests/test_pipeline/test_async_fan_out_does_not_hang.py +++ b/tests/test_pipeline/test_async_fan_out_does_not_hang.py @@ -12,13 +12,16 @@ rows than a channel holds, the upstream blocked and the run hung, with no fan-out. Each run here is awaited under ``asyncio.wait_for``: a deadlock fails the test with -``TimeoutError`` instead of hanging the suite. No test sleeps. +``TimeoutError`` instead of hanging the suite. The time limit is far above what a run +takes, since a deadlocked run never ends: a slow or busy runner must not fail a test +(ITL-1794). No test sleeps. """ from __future__ import annotations import asyncio import functools +import time from typing import Any import pytest @@ -56,10 +59,12 @@ def make_source(n_rows: int) -> DictSource: ) -def run_async_job(job: PipelineJob, buffer_size: int) -> None: +def run_async_job( + job: PipelineJob, buffer_size: int, timeout: float = RUN_TIMEOUT +) -> None: """Run ``job`` with the async orchestrator; fail with ``TimeoutError`` on a deadlock.""" orchestrator = AsyncPipelineOrchestrator(buffer_size=buffer_size) - asyncio.run(asyncio.wait_for(job.run_async(orchestrator=orchestrator), RUN_TIMEOUT)) + asyncio.run(asyncio.wait_for(job.run_async(orchestrator=orchestrator), timeout)) def output_rows(job: PipelineJob) -> list[dict[str, Any]]: @@ -152,19 +157,41 @@ def function_job(store: InMemoryArrowDatabase, n_rows: int) -> PipelineJob: return job -def test_function_fan_out_completes_when_every_row_is_stored() -> None: - """The second run, which finds every row stored, finishes with the rows of the first. +# The least time a run of ``function_job`` may take before it counts as deadlocked. +FUNCTION_RUN_TIMEOUT_FLOOR = 60.0 + +# How many times the sync run of the same graph, measured in the same test, a run of +# ``function_job`` may take. An async run takes about as long as the sync one. +FUNCTION_RUN_TIMEOUT_FACTOR = 10.0 + - 300 rows at buffer size 1 deadlocked on ``main``; 1,000 rows at 1, 16 and 64 are in - the measured table of the pull request (too slow for the default suite). +def test_function_fan_out_completes_when_every_row_is_stored() -> None: + """A run that finds every row stored finishes with the rows of a sync run. + + The first async run computes every row into the store; the second, by a new job over + the same store, finds every row stored and streams with backpressure, which + deadlocked on ``main`` (300 rows at buffer size 1; 1,000 rows at 1, 16 and 64 are in + the measured table of the pull request, too slow for the default suite). The second + run is a new job: the first job holds a current run of every node (ITL-1095), so + running it again computes and reads nothing. + + Each run's time limit is scaled from the sync run of the same graph on the same + runner, with a floor, so a slow runner cannot fail the test and a deadlock, which + never ends, still does (ITL-1794). """ + started = time.perf_counter() expected_job = function_job(InMemoryArrowDatabase(), 300) expected_job.run(orchestrator=SyncPipelineOrchestrator()) + sync_seconds = time.perf_counter() - started expected = expected_job.nodes["OUT"].as_table() + timeout = max( + FUNCTION_RUN_TIMEOUT_FLOOR, FUNCTION_RUN_TIMEOUT_FACTOR * sync_seconds + ) - job = function_job(InMemoryArrowDatabase(), 300) - for _ in range(2): - run_async_job(job, buffer_size=1) + store = InMemoryArrowDatabase() + for _ in range(2): # computes every row, then finds every row stored + job = function_job(store, 300) + run_async_job(job, buffer_size=1, timeout=timeout) got = job.nodes["OUT"].as_table() assert got.sort_by([("k", "ascending")]).equals( expected.sort_by([("k", "ascending")]) diff --git a/tests/test_pipeline/test_orchestrator_executor_matrix.py b/tests/test_pipeline/test_orchestrator_executor_matrix.py index 1cf2ec334..9f68307b4 100644 --- a/tests/test_pipeline/test_orchestrator_executor_matrix.py +++ b/tests/test_pipeline/test_orchestrator_executor_matrix.py @@ -31,6 +31,7 @@ from __future__ import annotations import asyncio +import threading import time from concurrent.futures import ThreadPoolExecutor @@ -142,10 +143,9 @@ async def slow_async_double(x: int) -> int: _POOL_WORKERS = 2 _POOL_N_DATA = 6 # 3× the pool size → at least 3 rounds for sync _POOL_SLEEP_S = 0.1 # per-data sleep -# async+async: all 6 run at once → ~0.1 s -# async+sync: 2 threads × 3 rounds → ~0.3 s -_POOL_ASYNC_MAX = _POOL_SLEEP_S * 2.0 # generous upper bound for async path -_POOL_SYNC_MIN = _POOL_SLEEP_S * 2.5 # conservative lower bound for sync path +# How long one async call waits for every call to be running at once before it gives +# up. Only a lost concurrency waits this long; it is far above any runner's delay. +_POOL_GIVE_UP_S = 30.0 # =========================================================================== @@ -488,6 +488,39 @@ def test_async_fn_concurrent_sync_fn_sequential_under_single_worker(self): # =========================================================================== +class _ConcurrencyCounter: + """Counts the calls of a function that are running, and the most at any moment. + + Safe to use from several threads. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self.reset() + + def reset(self) -> None: + """Forget every call counted so far.""" + with self._lock: + self.running = 0 + self.most = 0 + self.gave_up = False + + def enter(self) -> None: + """Record that a call started.""" + with self._lock: + self.running += 1 + self.most = max(self.most, self.running) + + def leave(self) -> None: + """Record that a call ended.""" + with self._lock: + self.running -= 1 + + +_sync_calls = _ConcurrencyCounter() +_async_calls = _ConcurrencyCounter() + + def _loop_sleep_double(x: int) -> int: """Sync function: sleeps via a for-loop of time.sleep calls. @@ -495,71 +528,82 @@ def _loop_sleep_double(x: int) -> int: function has no way to cooperate with an asyncio event loop. It occupies exactly one thread-pool slot for its entire duration. """ - steps = 5 - for _ in range(steps): - time.sleep(_POOL_SLEEP_S / steps) - return x * 2 + _sync_calls.enter() + try: + steps = 5 + for _ in range(steps): + time.sleep(_POOL_SLEEP_S / steps) + return x * 2 + finally: + _sync_calls.leave() async def _coro_sleep_double(x: int) -> int: - """Async function: same total sleep, but via a single asyncio.sleep. + """Async function: waits, cooperatively, until every call is running at once. - Suspends the coroutine cooperatively so the event loop can run other - coroutines during the wait — no thread needed. + Suspends the coroutine so the event loop can run other coroutines during the + wait: no thread needed. It returns once all ``_POOL_N_DATA`` calls are + running together, or after ``_POOL_GIVE_UP_S`` if they never are; then no + other call waits. """ - await asyncio.sleep(_POOL_SLEEP_S) - return x * 2 + _async_calls.enter() + try: + deadline = time.monotonic() + _POOL_GIVE_UP_S + # ``most`` never decreases: once every call ran at once, none waits. + while _async_calls.most < _POOL_N_DATA and not _async_calls.gave_up: + if time.monotonic() > deadline: + _async_calls.gave_up = True + break + await asyncio.sleep(0.01) + return x * 2 + finally: + _async_calls.leave() class TestAsyncAsyncVsAsyncSync: - """Verify that async+async outperforms async+sync when the thread pool - is smaller than the number of concurrent data. - - The sync function sleeps via a ``for`` loop of ``time.sleep`` calls — - unambiguously blocking with no event-loop cooperation. With only - ``_POOL_WORKERS`` thread slots available and ``_POOL_N_DATA`` data, - the async+sync path must serialise into multiple rounds. The async+async - path runs all coroutines concurrently regardless of the thread pool size. + """Async functions are not limited by the thread pool; sync functions are. + + The sync function sleeps via a ``for`` loop of ``time.sleep`` calls, + unambiguously blocking with no event-loop cooperation. With only + ``_POOL_WORKERS`` thread slots and ``_POOL_N_DATA`` data, at most + ``_POOL_WORKERS`` of its calls run at once. The async functions all run at + once, whatever the thread pool size. + + The test counts the calls running at once instead of timing the runs, so a + slow or busy runner cannot fail it (ITL-1794). """ def test_async_async_faster_than_async_sync_under_pool_saturation(self): - """async+async finishes in ~1 sleep period; async+sync needs multiple rounds.""" + """Every async call runs at once; sync calls are capped by the pool.""" expected = [x * 2 for x in range(_POOL_N_DATA)] # async+sync: for-loop sleep, thread pool capped at _POOL_WORKERS + _sync_calls.reset() p_sync = _build_pipeline( _loop_sleep_double, n=_POOL_N_DATA, max_concurrency=None ) - results_sync, elapsed_sync = asyncio.run( + results_sync, _ = asyncio.run( _run_async_with_limited_pool(p_sync, pool_workers=_POOL_WORKERS) ) assert results_sync == expected + assert _sync_calls.most <= _POOL_WORKERS, ( + f"{_sync_calls.most} sync calls ran at once; the thread pool has " + f"{_POOL_WORKERS} workers" + ) - # async+async: asyncio.sleep, all coroutines run concurrently + # async+async: all coroutines run concurrently + _async_calls.reset() p_async = _build_pipeline( _coro_sleep_double, n=_POOL_N_DATA, max_concurrency=None ) - results_async, elapsed_async = asyncio.run( + results_async, _ = asyncio.run( _run_async_with_limited_pool(p_async, pool_workers=_POOL_WORKERS) ) assert results_async == expected - - # async+async should complete in ~1 sleep period (all concurrent) - assert elapsed_async < _POOL_ASYNC_MAX, ( - f"async+async ({elapsed_async:.2f}s) should complete in ~1 sleep " - f"period (< {_POOL_ASYNC_MAX:.2f}s)" - ) - - # async+sync must take at least 2.5 sleep periods (pool saturated) - assert elapsed_sync >= _POOL_SYNC_MIN, ( - f"async+sync ({elapsed_sync:.2f}s) should be throttled by the " - f"thread pool to >= {_POOL_SYNC_MIN:.2f}s" - ) - - # and async+async must be clearly faster - assert elapsed_async < elapsed_sync * 0.6, ( - f"async+async ({elapsed_async:.2f}s) should be >40% faster than " - f"async+sync ({elapsed_sync:.2f}s) under pool saturation" + assert _async_calls.most == _POOL_N_DATA, ( + f"async+async should run all {_POOL_N_DATA} calls at once, whatever " + f"the thread pool size ({_POOL_WORKERS} workers); at most " + f"{_async_calls.most} ran at once" )