From af24c59f0e8149d9a02fe366eb51d33c7bbe6cd8 Mon Sep 17 00:00:00 2001 From: r0c0y <184822225+r0c0y@users.noreply.github.com> Date: Sun, 6 Dec 2026 06:37:36 +0530 Subject: [PATCH 1/2] Tell the points still running when an AsyncRunner reaches its goal #320 made BlockingRunner wait for the points the executor is still computing when the goal is reached and tell their results (#319). AsyncRunner got its futures from run_in_executor, and cancelling such a future marks it cancelled at once even when the executor is already running the point, so the evaluation finished in the worker and was dropped. Submit to the executor directly, keep its future, and when the goal is reached cancel only the points that are still queued and tell the running ones. cancel() and errors still stop at once. --- adaptive/runner.py | 48 +++++++++++++++++++++++++++---- adaptive/tests/test_runner.py | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/adaptive/runner.py b/adaptive/runner.py index 99f1f4e4..8607545a 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -500,6 +500,9 @@ class AsyncRunner(BaseRunner): stop requesting more points. If not provided, the runner will run forever (or stop when no more points can be added), or until ``runner.task.cancel()`` is called. + When the goal is reached, points that the executor is already + computing are waited for and told to the learner, as in + `BlockingRunner`; ``runner.cancel()`` does not wait for them. loss_goal : float, optional Convenience argument, use instead of ``goal``. The end condition for the calculation. Stop when the loss is smaller than this value. @@ -612,6 +615,10 @@ def __init__( ) self.ioloop = ioloop if ioloop is not None else _get_or_create_event_loop() + # The executor's own future behind each pending task, so that `_run` + # can tell a point that is still queued from one already running. + self._executor_futures: dict[asyncio.Future, concurrent.Future] = {} + # When the learned function is 'async def', we run it # directly on the event loop, and not in the executor. # The *whole point* of allowing learning of async functions is so that @@ -638,8 +645,29 @@ def _submit(self, x: Any) -> asyncio.Task | asyncio.Future: ioloop = self.ioloop if inspect.iscoroutinefunction(self.learner.function): return ioloop.create_task(self.learner.function(x)) - else: - return ioloop.run_in_executor(self.executor, self.learner.function, x) + # What `ioloop.run_in_executor` does, keeping the executor's future. + executor_future = self.executor.submit(self.learner.function, x) + future = asyncio.wrap_future(executor_future, loop=ioloop) + self._executor_futures[future] = executor_future + return future + + def _process_futures(self, done_futs: set[FutureTypes]) -> None: + for fut in done_futs: + self._executor_futures.pop(fut, None) # type: ignore[arg-type] + super()._process_futures(done_futs) + + async def _tell_running_points(self) -> None: + """Cancel the points still queued in the executor, and wait for the + ones it is already computing, which cannot be cancelled, to tell + their results to the learner, as `BlockingRunner` does.""" + running = [ + fut + for fut, executor_future in self._executor_futures.items() + if not executor_future.cancel() + ] + if running: + await asyncio.wait(running) + self._process_futures({fut for fut in running if not fut.cancelled()}) def status(self) -> str: """Return the runner status as a string. @@ -774,16 +802,24 @@ async def _run(self) -> None: if self._get_max_tasks() < 1: raise RuntimeError("Executor has no workers") + goal_reached = False try: while not self.goal(self.learner): futures = self._get_futures() done, _ = await asyncio.wait(futures, return_when=first_completed) # type: ignore[arg-type,type-var] self._process_futures(done) + goal_reached = True finally: - remaining = self._remove_unfinished() - if remaining: - await asyncio.wait(remaining) # type: ignore[type-var] - self._cleanup() + try: + # Only a reached goal waits: `cancel()` and errors stop at once. + if goal_reached: + await self._tell_running_points() + finally: + remaining = self._remove_unfinished() + if remaining: + await asyncio.wait(remaining) # type: ignore[type-var] + self._executor_futures.clear() + self._cleanup() def elapsed_time(self) -> float: """Return the total time elapsed since the runner diff --git a/adaptive/tests/test_runner.py b/adaptive/tests/test_runner.py index 0bb68c59..a3d8a729 100644 --- a/adaptive/tests/test_runner.py +++ b/adaptive/tests/test_runner.py @@ -1,6 +1,9 @@ +import asyncio import platform import sys +import threading import time +from concurrent.futures import ThreadPoolExecutor import numpy as np import pytest @@ -73,6 +76,56 @@ async def f(x): runner.block_until_done() +@pytest.mark.parametrize("runner_type", [BlockingRunner, AsyncRunner]) +def test_points_running_at_the_goal_are_told(runner_type): + # The upper bound is still being computed when the goal is reached. A + # running point cannot be cancelled, so the runner waits for it and tells + # the learner instead of dropping the result (#319). + calls = [] + + def f(x): + calls.append(x) + time.sleep(0.5 if x == 1 else 0.01) + return x + + learner = Learner1D(f, (-1, 1)) + with ThreadPoolExecutor(4) as executor: + runner = runner_type(learner, npoints_goal=10, executor=executor) + if isinstance(runner, AsyncRunner): + runner.block_until_done() + + assert 1 in learner.data + assert set(calls) == set(learner.data) + assert not learner.pending_points + + +def test_cancel_does_not_wait_for_running_points(): + # Only a goal waits for the points being computed: cancel() stops at once. + started = threading.Event() + + def f(x): + if x == 1: + started.set() + time.sleep(3) + return x + + executor = ThreadPoolExecutor(2) + runner = AsyncRunner(Learner1D(f, (-1, 1)), goal=lambda _: False, executor=executor) + + async def cancel_once_started(): + while not started.is_set(): + await asyncio.sleep(0.01) + runner.cancel() + + start = time.time() + runner.ioloop.run_until_complete(cancel_once_started()) + with pytest.raises(asyncio.CancelledError): + runner.block_until_done() + assert time.time() - start < 1.5 + assert runner.status() == "cancelled" + executor.shutdown(wait=False) + + # --- Test with different executors From d61bba624e0b787963748604e060d361812d1fca Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 20:58:09 -0800 Subject: [PATCH 2/2] Process AsyncRunner goal-drain results as they finish Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/runner.py | 20 +++++--- adaptive/tests/test_runner.py | 94 ++++++++++++++++++++++++++++------- 2 files changed, 88 insertions(+), 26 deletions(-) diff --git a/adaptive/runner.py b/adaptive/runner.py index 8607545a..d9744c9a 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -500,9 +500,11 @@ class AsyncRunner(BaseRunner): stop requesting more points. If not provided, the runner will run forever (or stop when no more points can be added), or until ``runner.task.cancel()`` is called. - When the goal is reached, points that the executor is already - computing are waited for and told to the learner, as in - `BlockingRunner`; ``runner.cancel()`` does not wait for them. + When a goal is reached, including a time-based goal, the runner waits + for points already running that the executor cannot cancel, as in + `BlockingRunner`. It tells the learner their results as they finish. + ``runner.cancel()`` does not wait for them unless + ``shutdown_executor=True``. loss_goal : float, optional Convenience argument, use instead of ``goal``. The end condition for the calculation. Stop when the loss is smaller than this value. @@ -660,14 +662,16 @@ async def _tell_running_points(self) -> None: """Cancel the points still queued in the executor, and wait for the ones it is already computing, which cannot be cancelled, to tell their results to the learner, as `BlockingRunner` does.""" - running = [ + pending = { fut for fut, executor_future in self._executor_futures.items() if not executor_future.cancel() - ] - if running: - await asyncio.wait(running) - self._process_futures({fut for fut in running if not fut.cancelled()}) + } + while pending: + done, pending = await asyncio.wait( + pending, return_when=asyncio.FIRST_COMPLETED + ) + self._process_futures({fut for fut in done if not fut.cancelled()}) def status(self) -> str: """Return the runner status as a string. diff --git a/adaptive/tests/test_runner.py b/adaptive/tests/test_runner.py index a3d8a729..ab327134 100644 --- a/adaptive/tests/test_runner.py +++ b/adaptive/tests/test_runner.py @@ -4,6 +4,7 @@ import threading import time from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager import numpy as np import pytest @@ -101,29 +102,86 @@ def f(x): def test_cancel_does_not_wait_for_running_points(): # Only a goal waits for the points being computed: cancel() stops at once. - started = threading.Event() + release = threading.Event() + finished = threading.Event() def f(x): if x == 1: - started.set() - time.sleep(3) + runner.ioloop.call_soon_threadsafe(runner.cancel) + release.wait(timeout=5) + finished.set() return x - executor = ThreadPoolExecutor(2) - runner = AsyncRunner(Learner1D(f, (-1, 1)), goal=lambda _: False, executor=executor) - - async def cancel_once_started(): - while not started.is_set(): - await asyncio.sleep(0.01) - runner.cancel() - - start = time.time() - runner.ioloop.run_until_complete(cancel_once_started()) - with pytest.raises(asyncio.CancelledError): - runner.block_until_done() - assert time.time() - start < 1.5 - assert runner.status() == "cancelled" - executor.shutdown(wait=False) + with ThreadPoolExecutor(2) as executor: + learner = Learner1D(f, (-1, 1)) + runner = AsyncRunner(learner, goal=lambda _: False, executor=executor) + try: + with pytest.raises(asyncio.CancelledError): + runner.block_until_done() + assert runner.status() == "cancelled" + assert not finished.is_set() + finally: + release.set() + + +@contextmanager +def _goal_drain_runner(*, fail_second=False): + all_started = threading.Barrier(3) + release_second = threading.Event() + release = threading.Event() + straggler_finished = threading.Event() + + def f(x): + all_started.wait(timeout=5) + if x == 2: + assert release_second.wait(timeout=5) + if fail_second: + raise ValueError("boom") + elif x == 3: + release.wait(timeout=5) + straggler_finished.set() + return x + + class NotifyingLearner(Learner1D): + def tell(self, x, y): + super().tell(x, y) + if x == 1: + # Point 2 can finish only after point 1 satisfies the goal. + release_second.set() + elif x == 2: + second_told.set_result(None) + + with ThreadPoolExecutor(3) as executor: + learner = NotifyingLearner(f, (1, 3)) + runner = AsyncRunner(learner, npoints_goal=1, executor=executor) + second_told = runner.ioloop.create_future() + try: + yield runner, second_told, straggler_finished + finally: + release_second.set() + release.set() + + +def test_cancel_during_goal_drain_preserves_finished_points(): + with _goal_drain_runner() as (runner, second_told, straggler_finished): + second_told.add_done_callback(lambda _: runner.cancel()) + with pytest.raises(asyncio.CancelledError): + runner.block_until_done() + assert runner.status() == "cancelled" + assert set(runner.learner.data) == {1, 2} + assert not runner.learner.pending_points + assert not straggler_finished.is_set() + + +def test_error_during_goal_drain_fails_immediately(): + with _goal_drain_runner(fail_second=True) as (runner, _, straggler_finished): + with pytest.raises(RuntimeError) as exc_info: + runner.block_until_done() + cause = exc_info.value.__cause__ + assert isinstance(cause, ValueError) + assert str(cause) == "boom" + assert runner.status() == "failed" + assert not straggler_finished.is_set() # --- Test with different executors