diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 9891513a..0f1e93e6 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1156,6 +1156,7 @@ async def start( run_name: str | None = None, abort_with_parent: bool | None = None, resurrect_with_parent: bool | None = None, + wait_for_resources: bool | timedelta | None = None, ) -> Run: """Run an Actor on the Apify platform. @@ -1204,6 +1205,12 @@ async def start( after the abort, typically after this Actor run was resurrected. A child run that failed, timed out or was aborted by someone else is not resurrected. The value is recorded the same way as `abort_with_parent`, and without a `run_name` it needs `Configuration.persist_unnamed_child_runs`. + wait_for_resources: Whether to retry the start while the account lacks the memory or a concurrent-run slot + for the run. The start is retried every 10 seconds. `True` retries until the run starts, and a + `timedelta` stops after that time and raises the last error. A run that asks for more memory than the + account has in total never starts, so `True` retries it forever. It has no effect on a call that returns + a recorded run. Once this Actor run is being gracefully aborted, a tracked start that waits for + resources raises a `RuntimeError`. Returns: Info about the started Actor run @@ -1245,7 +1252,9 @@ async def start( ) if not is_tracked: - return await start_run(run_timeout=self._resolve_run_timeout(timeout)) + return await start_run( + run_timeout=self._resolve_run_timeout(timeout), wait_for_resources=wait_for_resources or False + ) _, run, _ = await self._find_or_start_child_run( run_name, @@ -1267,6 +1276,7 @@ async def start( timeout=timeout, abort_with_parent=abort_with_parent, resurrect_with_parent=resurrect_with_parent, + wait_for_resources=wait_for_resources, ) return run @@ -1383,6 +1393,7 @@ async def call( run_name: str | None = None, abort_with_parent: bool | None = None, resurrect_with_parent: bool | None = None, + wait_for_resources: bool | timedelta | None = None, ) -> Run: """Start an Actor on the Apify Platform and wait for it to finish before returning. @@ -1434,6 +1445,12 @@ async def call( after the abort, typically after this Actor run was resurrected. A child run that failed, timed out or was aborted by someone else is not resurrected. The value is recorded the same way as `abort_with_parent`, and without a `run_name` it needs `Configuration.persist_unnamed_child_runs`. + wait_for_resources: Whether to retry the start while the account lacks the memory or a concurrent-run slot + for the run. The start is retried every 10 seconds. `True` retries until the run starts, and a + `timedelta` stops after that time and raises the last error. A run that asks for more memory than the + account has in total never starts, so `True` retries it forever. It has no effect on a call that returns + a recorded run. Once this Actor run is being gracefully aborted, a tracked start that waits for + resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1476,6 +1493,7 @@ async def call( webhooks=to_client_representations(webhooks), wait_duration=wait, logger=logger, + wait_for_resources=wait_for_resources or False, ) else: key, started_run, is_new = await self._find_or_start_child_run( @@ -1509,6 +1527,7 @@ async def call( timeout=timeout, abort_with_parent=abort_with_parent, resurrect_with_parent=resurrect_with_parent, + wait_for_resources=wait_for_resources, ) # An earlier process of this Actor run already streamed the start of the log of a recorded run. run = await self._wait_for_child_run( @@ -1534,6 +1553,7 @@ async def _find_or_start_child_run( timeout: timedelta | Literal['inherit'] | None, abort_with_parent: bool | None, resurrect_with_parent: bool | None, + wait_for_resources: bool | timedelta | None, ) -> tuple[ChildRunKey, Run, bool]: checksum = checksum_request( actor_id=actor_id, @@ -1559,6 +1579,7 @@ async def start_run_with_timeout() -> Run: start_run=start_run_with_timeout, abort_with_parent=abort_with_parent, resurrect_with_parent=resurrect_with_parent, + wait_for_resources=wait_for_resources or False, ) return key, run, is_new @@ -1627,6 +1648,7 @@ async def start_task( run_name: str | None = None, abort_with_parent: bool | None = None, resurrect_with_parent: bool | None = None, + wait_for_resources: bool | timedelta | None = None, ) -> Run: """Start an Actor task on the Apify Platform. @@ -1675,6 +1697,12 @@ async def start_task( after the abort, typically after this Actor run was resurrected. A child run that failed, timed out or was aborted by someone else is not resurrected. The value is recorded the same way as `abort_with_parent`, and without a `run_name` it needs `Configuration.persist_unnamed_child_runs`. + wait_for_resources: Whether to retry the start while the account lacks the memory or a concurrent-run slot + for the run. The start is retried every 10 seconds. `True` retries until the run starts, and a + `timedelta` stops after that time and raises the last error. A run that asks for more memory than the + account has in total never starts, so `True` retries it forever. It has no effect on a call that returns + a recorded run. Once this Actor run is being gracefully aborted, a tracked start that waits for + resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1713,7 +1741,9 @@ async def start_task( ) if not is_tracked: - return await start_run(run_timeout=self._resolve_run_timeout(timeout)) + return await start_run( + run_timeout=self._resolve_run_timeout(timeout), wait_for_resources=wait_for_resources or False + ) _, run, _ = await self._find_or_start_child_run( run_name, @@ -1733,6 +1763,7 @@ async def start_task( timeout=timeout, abort_with_parent=abort_with_parent, resurrect_with_parent=resurrect_with_parent, + wait_for_resources=wait_for_resources, ) return run @@ -1754,6 +1785,7 @@ async def call_task( run_name: str | None = None, abort_with_parent: bool | None = None, resurrect_with_parent: bool | None = None, + wait_for_resources: bool | timedelta | None = None, ) -> Run: """Start an Actor task on the Apify Platform and wait for it to finish before returning. @@ -1802,6 +1834,12 @@ async def call_task( after the abort, typically after this Actor run was resurrected. A child run that failed, timed out or was aborted by someone else is not resurrected. The value is recorded the same way as `abort_with_parent`, and without a `run_name` it needs `Configuration.persist_unnamed_child_runs`. + wait_for_resources: Whether to retry the start while the account lacks the memory or a concurrent-run slot + for the run. The start is retried every 10 seconds. `True` retries until the run starts, and a + `timedelta` stops after that time and raises the last error. A run that asks for more memory than the + account has in total never starts, so `True` retries it forever. It has no effect on a call that returns + a recorded run. Once this Actor run is being gracefully aborted, a tracked start that waits for + resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1841,6 +1879,7 @@ async def call_task( run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), wait_duration=wait, + wait_for_resources=wait_for_resources or False, ) else: key, started_run, _ = await self._find_or_start_child_run( @@ -1870,6 +1909,7 @@ async def call_task( timeout=timeout, abort_with_parent=abort_with_parent, resurrect_with_parent=resurrect_with_parent, + wait_for_resources=wait_for_resources, ) run = await self._wait_for_child_run( key, client.run(started_run.id), started_run, wait=wait, logger=None, from_start=False diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index ad9c9d96..9d7afe3d 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -14,7 +14,7 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError from pydantic.alias_generators import to_camel -from apify_client.errors import NotFoundError +from apify_client.errors import ApifyApiError, NotFoundError from apify_client.http_clients import StreamedRequestBody from apify._utils import docs_group @@ -55,6 +55,12 @@ _STARTS_IN_FLIGHT_TIMEOUT = timedelta(seconds=10) """How long a reboot or metamorph of the parent waits for the start requests that are already sent.""" +_RESOURCE_LIMIT_ERROR_TYPES = frozenset({'actor-memory-limit-exceeded', 'concurrent-runs-limit-exceeded'}) +"""Error types the API rejects a run start with while the account lacks the memory or a run slot for it.""" + +_WAIT_FOR_RESOURCES_COOLDOWN = timedelta(seconds=10) +"""Time between two attempts to start a run that the API rejected for lack of account resources.""" + _NOT_FOUND_GRACE_SECS = 3 """How long a recorded run that the API reports as missing is looked up again before it counts as gone.""" @@ -364,6 +370,8 @@ def __init__( """Client the run under each key was last started or looked up with. Lost with the process.""" self._parent_aborting = False """Whether this Actor run is being gracefully aborted, after which no run marked `abort_with_parent` starts.""" + self._parent_aborting_event = asyncio.Event() + """Set together with `_parent_aborting`, to wake up the starts that wait for account resources.""" self._abort_task: asyncio.Task[None] | None = None """The abort of the child runs with the parent, once the parent is being gracefully aborted.""" self._starts_in_flight = 0 @@ -383,6 +391,7 @@ async def find_or_start( start_run: Callable[[], Awaitable[Run]], abort_with_parent: bool | None = None, resurrect_with_parent: bool | None = None, + wait_for_resources: bool | timedelta = False, ) -> tuple[Run, bool]: """Return the run recorded under `key`, or start one when there is none. @@ -400,6 +409,9 @@ async def find_or_start( replaces the value recorded under `key`. `None` keeps it, and is `False` for a key with no record. resurrect_with_parent: Whether to resurrect the run after it was aborted with this Actor run. The value is recorded the same way as `abort_with_parent`. + wait_for_resources: Whether to retry starting a new run while the API rejects it for the memory or + concurrent-run limit of the account. `True` retries until the run starts, and a `timedelta` stops after + that time and raises the last error. Returns: The run, and whether it was newly started. @@ -407,7 +419,8 @@ async def find_or_start( Raises: ValueError: If the run recorded under `key` was started with a different request. RuntimeError: If this Actor run is being gracefully aborted, and a new run marked `abort_with_parent` - would start, or a run would have to wait for the concurrency limit. No run is started. + would start, or a run would have to wait for the concurrency limit or for account resources. No run + is started. """ async with self._key_locks.setdefault(key, asyncio.Lock()): record = self._records(key.kind).get(key.key) @@ -470,6 +483,11 @@ async def find_or_start( extra={'run_id': record.run_id}, ) + # The time limit of `wait_for_resources` also covers the wait for a slot. + deadline = None + if isinstance(wait_for_resources, timedelta): + deadline = asyncio.get_running_loop().time() + wait_for_resources.total_seconds() + if not await self._reserve_slot(key): raise RuntimeError( f'Child run "{key.key}" was not started, since this Actor run is being aborted and the limit of ' @@ -482,29 +500,71 @@ async def find_or_start( f'Child run "{key.key}" with `abort_with_parent` was not started, since this Actor run is ' 'being aborted.' ) - # A parent that is about to reboot or metamorph sends no more start requests. - await self._starts_allowed.wait() - with self._start_in_flight(): - run = await start_run() - new_record = ChildRunRecord( - run_id=run.id, - run_name=key.key if key.kind == 'named' else None, - status=run.status, - checksum=checksum, - abort_with_parent=abort_with_parent, - resurrect_with_parent=resurrect_with_parent, - # An abort that started while the start request was in flight waits for this key, and - # then aborts the run. - aborted_with_parent=abort_with_parent and self._is_abort_in_progress(), - ) - self._mark_observed(key) - await self._save(key, new_record) + while True: + try: + # A parent that is about to reboot or metamorph sends no more start requests. + await self._starts_allowed.wait() + with self._start_in_flight(): + run = await start_run() + new_record = ChildRunRecord( + run_id=run.id, + run_name=key.key if key.kind == 'named' else None, + status=run.status, + checksum=checksum, + abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, + # An abort that started while the start request was in flight waits for this key, and + # then aborts the run. + aborted_with_parent=abort_with_parent and self._is_abort_in_progress(), + ) + self._mark_observed(key) + await self._save(key, new_record) + break + except ApifyApiError as exc: + if wait_for_resources is False or exc.type not in _RESOURCE_LIMIT_ERROR_TYPES: + raise + await self._wait_for_resources(key, exc, deadline) finally: # A recorded run counts toward the limit through its record, and a failed start holds no slot. await self._release_reserved_slot() self._clients[key] = client return run, True + async def _wait_for_resources(self, key: ChildRunKey, exc: ApifyApiError, deadline: float | None) -> None: + """Wait before the next attempt to start a run that the API rejected for lack of account resources. + + Args: + key: Key of the child run. + exc: The error of the rejected start. + deadline: Event loop time at which the retrying stops, or `None` to retry until the run starts. + + Raises: + ApifyApiError: `exc`, if the deadline passed. + RuntimeError: If this Actor run is being gracefully aborted. + """ + delay = _WAIT_FOR_RESOURCES_COOLDOWN.total_seconds() + if deadline is not None: + remaining = deadline - asyncio.get_running_loop().time() + if remaining <= 0: + raise exc + delay = min(delay, remaining) + + if not self._parent_aborting: + logger.info( + 'Not enough resources to start child run "%s", retrying in %.3gs: %s', key.key, delay, exc.message + ) + try: + async with asyncio.timeout(delay): + await self._parent_aborting_event.wait() + except TimeoutError: + return + + # The parent is killed soon, and its abort waits for the lock of this key. + raise RuntimeError( + f'Child run "{key.key}" was not started, since this Actor run is being aborted and the account lacks ' + 'the resources for the run.' + ) from exc + @contextmanager def _start_in_flight(self) -> Generator[None]: """Count a start from the moment its request is sent until its run is recorded.""" @@ -555,9 +615,8 @@ async def _resurrect_with_parent( The run, or `None` if the API no longer knows it, and whether it still counts as aborted with the parent. """ if not self._parent_aborting and not self._parent_status_checked and self._is_parent_aborting is not None: - # The answer only ever raises the flag, since `ABORTING` can arrive while the request is in flight. if await self._is_parent_aborting(): - self._parent_aborting = True + self._set_parent_aborting() self._parent_status_checked = True # The process that aborts the children must not resurrect them. @@ -783,12 +842,16 @@ async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: client: Client used for a key not started or looked up in this process, e.g. one recorded by an earlier process of this Actor run. """ - self._parent_aborting = True + self._set_parent_aborting() if self._abort_task is None: self._abort_task = asyncio.create_task(self._abort_runs_with_parent(client)) # The abort outlives a caller that stops waiting for it, e.g. a listener cancelled on its timeout. await asyncio.shield(self._abort_task) + def _set_parent_aborting(self) -> None: + self._parent_aborting = True + self._parent_aborting_event.set() + async def wait_for_abort(self) -> None: """Wait until the abort of the child runs with the parent finishes, if it has started.""" if self._abort_task is not None: diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index c791a059..cfd01ae4 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -13,7 +13,7 @@ from pydantic import ValidationError from apify_client._models import Run -from apify_client.errors import NotFoundError +from apify_client.errors import ApifyApiError, NotFoundError from crawlee import service_locator from crawlee.events import Event, EventAbortingData @@ -127,6 +127,13 @@ async def wait_until_blocked(task: asyncio.Task[Any]) -> None: assert not task.done() +def make_resource_limit_error(error_type: str = 'actor-memory-limit-exceeded') -> ApifyApiError: + """Build the error the API rejects a run start with while the account lacks resources for the run.""" + payload = {'error': {'type': error_type, 'message': 'Not enough resources'}} + response = Mock(status_code=402, text='', json=Mock(return_value=payload)) + return ApifyApiError(response, 1, method='POST') + + def stored_registry( named: dict[str, dict[str, Any]] | None = None, unnamed: dict[str, dict[str, Any]] | None = None ) -> dict[str, Any]: @@ -2696,6 +2703,209 @@ async def test_no_limit_fetches_no_runs(apify_client_async_patcher: ApifyClientA assert fetched_run_ids == [] +@pytest.mark.parametrize( + ('method', 'resource', 'submethod'), + [ + pytest.param('start', 'actor', 'start', id='start'), + pytest.param('call', 'actor', 'call', id='call'), + pytest.param('start_task', 'task', 'start', id='start task'), + pytest.param('call_task', 'task', 'call', id='call task'), + ], +) +@pytest.mark.parametrize( + ('wait_for_resources', 'forwarded'), + [ + pytest.param(None, False, id='none'), + pytest.param(True, True, id='true'), + pytest.param(timedelta(minutes=5), timedelta(minutes=5), id='timedelta'), + ], +) +async def test_untracked_run_forwards_wait_for_resources_to_the_client( + apify_client_async_patcher: ApifyClientAsyncPatcher, + *, + method: str, + resource: str, + submethod: str, + wait_for_resources: bool | timedelta | None, + forwarded: bool | timedelta, +) -> None: + """With persistence off, a call without a name passes `wait_for_resources` to the client.""" + apify_client_async_patcher.patch(resource, submethod, return_value=make_run('new-run', 'SUCCEEDED')) + + async with Actor: + await getattr(Actor, method)('some-id', wait_for_resources=wait_for_resources) + + [(_, kwargs)] = apify_client_async_patcher.calls[resource][submethod] + assert kwargs['wait_for_resources'] == forwarded + + +@pytest.mark.parametrize( + ('method', 'resource'), + [ + pytest.param('start', 'actor', id='start'), + pytest.param('call', 'actor', id='call'), + pytest.param('start_task', 'task', id='start task'), + pytest.param('call_task', 'task', id='call task'), + ], +) +@pytest.mark.parametrize( + 'error_type', + [ + pytest.param('actor-memory-limit-exceeded', id='memory limit'), + pytest.param('concurrent-runs-limit-exceeded', id='concurrent runs limit'), + ], +) +async def test_tracked_start_retries_while_the_account_lacks_resources( + apify_client_async_patcher: ApifyClientAsyncPatcher, + monkeypatch: pytest.MonkeyPatch, + method: str, + resource: str, + error_type: str, +) -> None: + """A tracked start with `wait_for_resources` is retried after the API rejects it for the account limits.""" + monkeypatch.setattr(_child_runs, '_WAIT_FOR_RESOURCES_COOLDOWN', timedelta(milliseconds=10)) + rejection = make_resource_limit_error(error_type) + start_run = Mock(side_effect=[rejection, rejection, make_run('new-run', 'READY')]) + apify_client_async_patcher.patch(resource, 'start', replacement_method=start_run) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) + kwargs = {'logger': None} if method == 'call' else {} + + async with Actor: + run = await getattr(Actor, method)('some-id', run_name='scrape-eu', wait_for_resources=True, **kwargs) + child_runs = Actor.child_runs + + assert run.id == 'new-run' + assert start_run.call_count == 3 + assert all('wait_for_resources' not in call.kwargs for call in start_run.call_args_list) + assert child_runs.named['scrape-eu'].record.run_id == 'new-run' + + +@pytest.mark.parametrize( + ('wait_for_resources', 'error'), + [ + pytest.param(None, make_resource_limit_error(), id='resources not waited for'), + pytest.param(False, make_resource_limit_error(), id='resources not waited for explicitly'), + pytest.param(True, RuntimeError('other error'), id='other error'), + pytest.param(True, make_resource_limit_error('actor-not-found'), id='other API error'), + ], +) +async def test_tracked_start_does_not_retry_other_failures( + apify_client_async_patcher: ApifyClientAsyncPatcher, + *, + wait_for_resources: bool | None, + error: Exception, +) -> None: + """A tracked start raises right away without `wait_for_resources`, or for an error that is not about resources.""" + start_run = Mock(side_effect=error) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + + async with Actor: + with pytest.raises(type(error)): + await Actor.start('some-actor', run_name='scrape-eu', wait_for_resources=wait_for_resources) + child_runs = Actor.child_runs + + assert start_run.call_count == 1 + assert child_runs == ChildRuns(named={}, unnamed={}) + + +async def test_tracked_start_stops_waiting_for_resources_after_the_given_time( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """A tracked start with a `timedelta` raises the last error once that time passed.""" + monkeypatch.setattr(_child_runs, '_WAIT_FOR_RESOURCES_COOLDOWN', timedelta(milliseconds=5)) + start_run = Mock(side_effect=make_resource_limit_error()) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + + async with Actor: + with pytest.raises(ApifyApiError, match='Not enough resources'): + await asyncio.wait_for( + Actor.start('some-actor', run_name='scrape-eu', wait_for_resources=timedelta(milliseconds=200)), + timeout=5, + ) + + assert start_run.call_count >= 2 + + +async def test_wait_for_resources_does_nothing_for_a_recorded_run( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A call with `wait_for_resources` under a recorded key returns the recorded run and starts nothing.""" + apify_client_async_patcher.patch('actor', 'start', replacement_method=Mock(side_effect=make_resource_limit_error())) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'FAILED')) + + async with Actor: + await record_child_run('scrape-eu', 'old-run') + run = await Actor.start('some-actor', run_name='scrape-eu', wait_for_resources=True) + + assert run.id == 'old-run' + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +async def test_start_waiting_for_resources_raises_once_aborting( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """After `ABORTING`, a tracked start that waits for resources raises and starts no run.""" + start_run = Mock(side_effect=make_resource_limit_error()) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + + async with Actor: + waiting_start = asyncio.create_task( + Actor.start('some-actor', run_name='scrape-eu', abort_with_parent=True, wait_for_resources=True) + ) + await wait_until_blocked(waiting_start) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + with pytest.raises(RuntimeError, match='the account lacks the resources for the run'): + await asyncio.wait_for(waiting_start, timeout=1) + await asyncio.wait_for(apify_event_manager.wait_for_all_listeners_to_complete(), timeout=1) + with pytest.raises(RuntimeError, match='the account lacks the resources for the run'): + await asyncio.wait_for(Actor.start('some-actor', run_name='scrape-us', wait_for_resources=True), timeout=1) + child_runs = Actor.child_runs + + assert start_run.call_count == 2 + assert child_runs == ChildRuns(named={}, unnamed={}) + + +async def test_start_waiting_for_resources_holds_its_slot_of_the_limit( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A start that waits for resources counts toward the concurrency limit, so the next start waits for a slot.""" + start_run = Mock(side_effect=make_resource_limit_error()) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + + async with Actor(max_concurrent_child_runs=1): + waiting_for_resources = asyncio.create_task( + Actor.start('some-actor', run_name='scrape-eu', wait_for_resources=True) + ) + await wait_until_blocked(waiting_for_resources) + waiting_for_slot = asyncio.create_task(Actor.start('some-actor', run_name='scrape-us')) + await wait_until_blocked(waiting_for_slot) + for task in (waiting_for_resources, waiting_for_slot): + task.cancel() + await asyncio.gather(waiting_for_resources, waiting_for_slot, return_exceptions=True) + + assert start_run.call_count == 1 + + +async def test_reboot_does_not_wait_for_a_start_that_waits_for_resources( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reboot is requested right away when the only start in progress waits for account resources.""" + apify_client_async_patcher.patch('actor', 'start', replacement_method=Mock(side_effect=make_resource_limit_error())) + apify_client_async_patcher.patch('run', 'reboot', return_value=None) + + async with Actor: + # Only the check in the method sees the platform, so the storages stay local. + monkeypatch.setattr(_ActorType, 'is_at_home', lambda _self: True) + Actor.configuration.actor_run_id = 'some-run-id' + waiting_start = asyncio.create_task(Actor.start('some-actor', run_name='scrape-eu', wait_for_resources=True)) + await wait_until_blocked(waiting_start) + await asyncio.wait_for(Actor.reboot(custom_after_sleep=timedelta(0)), timeout=1) + waiting_start.cancel() + await asyncio.gather(waiting_start, return_exceptions=True) + + assert len(apify_client_async_patcher.calls['run']['reboot']) == 1 + + async def test_aborting_event_before_the_registry_is_loaded_waits_for_it() -> None: """An abort of the child runs that starts before the registry is loaded aborts the recorded runs after the load.""" client = Mock()