Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 46 additions & 6 deletions adaptive/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +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 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.
Expand Down Expand Up @@ -612,6 +617,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
Expand All @@ -638,8 +647,31 @@ 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."""
pending = {
fut
for fut, executor_future in self._executor_futures.items()
if not executor_future.cancel()
}
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.
Expand Down Expand Up @@ -774,16 +806,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
Expand Down
111 changes: 111 additions & 0 deletions adaptive/tests/test_runner.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import asyncio
import platform
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager

import numpy as np
import pytest
Expand Down Expand Up @@ -73,6 +77,113 @@ 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.
release = threading.Event()
finished = threading.Event()

def f(x):
if x == 1:
runner.ioloop.call_soon_threadsafe(runner.cancel)
release.wait(timeout=5)
finished.set()
return x

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


Expand Down
Loading