diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 9404460e..d41d069d 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1183,6 +1183,7 @@ async def start( webhooks: list[Webhook] | None = None, run_name: str | None = None, abort_with_parent: bool | None = None, + wait_for_resources: bool | timedelta = False, ) -> Run: """Run an Actor on the Apify platform. @@ -1229,6 +1230,12 @@ async def start( and `False` replace the recorded value and `None` keeps it. Once the child runs are being aborted, a call that would start a new run with it raises a `RuntimeError`. It needs child run tracking and cannot be combined with a custom `token`. + 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. Nothing is recorded while the start is retried, and once this Actor run is + being aborted, a start that waits for resources raises a `RuntimeError`. Returns: Info about the started Actor run @@ -1269,6 +1276,7 @@ async def start( webhooks=to_client_representations(webhooks), ), abort_with_parent=abort_with_parent, + wait_for_resources=wait_for_resources, ) return run @@ -1384,6 +1392,7 @@ async def call( logger: logging.Logger | Literal['default'] | None = 'default', run_name: str | None = None, abort_with_parent: bool | None = None, + wait_for_resources: bool | timedelta = False, ) -> Run: """Start an Actor on the Apify Platform and wait for it to finish before returning. @@ -1433,6 +1442,12 @@ async def call( and `False` replace the recorded value and `None` keeps it. Once the child runs are being aborted, a call that would start a new run with it raises a `RuntimeError`. It needs child run tracking and cannot be combined with a custom `token`. + 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. Nothing is recorded while the start is retried, and once this Actor run is + being aborted, a start that waits for resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1473,6 +1488,7 @@ async def call( webhooks=to_client_representations(webhooks), ), abort_with_parent=abort_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( @@ -1515,6 +1531,7 @@ async def _start_child_run( content_type: str | None = None, options: dict[str, Any], abort_with_parent: bool | None, + wait_for_resources: bool | timedelta, ) -> tuple[Run, str | None, bool]: """Start a child run and record it, or return the run recorded under its explicit or implicit run name. @@ -1531,12 +1548,15 @@ def start_run_now(**kwargs: Any) -> Awaitable[Run]: return start_run(run_timeout=self._resolve_run_timeout(timeout), **kwargs) if not self._child_run_registry.is_enabled: - return await start_run_now(), None, True + return await start_run_now(wait_for_resources=wait_for_resources), None, True is_implicit = run_name is None and self.configuration.auto_memoize_child_runs if run_name is None and not is_implicit: run, key = await self._child_run_registry.start( - client=client, start_run=start_run_now, abort_with_parent=bool(abort_with_parent) + client=client, + start_run=start_run_now, + abort_with_parent=bool(abort_with_parent), + wait_for_resources=wait_for_resources, ) return run, key, True @@ -1556,6 +1576,7 @@ def start_run_now(**kwargs: Any) -> Awaitable[Run]: client=client, start_run=start_run_now, abort_with_parent=abort_with_parent, + wait_for_resources=wait_for_resources, ) return run, key, is_new @@ -1632,6 +1653,7 @@ async def start_task( token: str | None = None, run_name: str | None = None, abort_with_parent: bool | None = None, + wait_for_resources: bool | timedelta = False, ) -> Run: """Start an Actor task on the Apify Platform. @@ -1678,6 +1700,12 @@ async def start_task( and `False` replace the recorded value and `None` keeps it. Once the child runs are being aborted, a call that would start a new run with it raises a `RuntimeError`. It needs child run tracking and cannot be combined with a custom `token`. + 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. Nothing is recorded while the start is retried, and once this Actor run is + being aborted, a start that waits for resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1711,6 +1739,7 @@ async def start_task( run_input=task_input, options=checksum_run_options(build=build, webhooks=to_client_representations(webhooks)), abort_with_parent=abort_with_parent, + wait_for_resources=wait_for_resources, ) return run @@ -1732,6 +1761,7 @@ async def call_task( token: str | None = None, run_name: str | None = None, abort_with_parent: bool | None = None, + wait_for_resources: bool | timedelta = False, ) -> Run: """Start an Actor task on the Apify Platform and wait for it to finish before returning. @@ -1783,6 +1813,12 @@ async def call_task( and `False` replace the recorded value and `None` keeps it. Once the child runs are being aborted, a call that would start a new run with it raises a `RuntimeError`. It needs child run tracking and cannot be combined with a custom `token`. + 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. Nothing is recorded while the start is retried, and once this Actor run is + being aborted, a start that waits for resources raises a `RuntimeError`. Returns: Info about the started Actor run. @@ -1818,6 +1854,7 @@ async def call_task( run_input=task_input, options=checksum_run_options(build=build, webhooks=to_client_representations(webhooks)), abort_with_parent=abort_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( diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index d62be92b..87483923 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -7,6 +7,7 @@ import math from abc import ABC, abstractmethod from contextlib import asynccontextmanager, suppress +from datetime import timedelta from logging import getLogger from typing import TYPE_CHECKING, Any, NamedTuple from weakref import WeakValueDictionary @@ -14,7 +15,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 @@ -48,6 +49,12 @@ STATUS_MAX_AGE_SECS = 10 """How long an observed active status counts toward the concurrency limit before the run is fetched again.""" +_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_SECS = 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.""" @@ -395,6 +402,8 @@ def __init__( """Client the run under each key was last started or looked up with. Lost with the process.""" self._abort_task: asyncio.Task[None] | None = None """Aborts the runs marked `abort_with_parent`. Once it exists, no new run marked `abort_with_parent` starts.""" + self._abort_started = asyncio.Event() + """Set once the abort begins, to wake up the starts that wait for account resources.""" self._start_ids = itertools.count() self._warned_excessive_runs = False self._starts_in_flight = 0 @@ -420,6 +429,7 @@ async def find_or_start( client: ApifyClientAsync, start_run: Callable[[], Awaitable[Run]], abort_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. @@ -434,13 +444,17 @@ async def find_or_start( start_run: Starts a new run of the Actor or task. abort_with_parent: Whether to abort the run when this Actor run is aborted. `True` and `False` replace the value recorded under `key`, and `None` keeps it. A new run records `None` as `False`. + 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. Raises: ValueError: If the run recorded under `key` was started with a different request. - RuntimeError: If a new run with `abort_with_parent` would start while this Actor run is being aborted. + RuntimeError: If a new run with `abort_with_parent` would start while this Actor run is being aborted, or + a new run would have to wait for account resources then. """ async with self._key_locks.setdefault(key, asyncio.Lock()): record = self._get_records().get(key) @@ -473,8 +487,8 @@ async def find_or_start( ) self._check_not_aborting(key, abort_with_parent=bool(abort_with_parent)) - async with self._start_in_flight(key): - run = await start_run() + + async def record_run(run: Run) -> str: new_record = ChildRunRecord( run_id=run.id, status=run.status, @@ -482,6 +496,11 @@ async def find_or_start( checksum=checksum, ) await self._store(key, new_record) + return key + + run, _ = await self._start_with_retries( + key, start_run=start_run, record_run=record_run, wait_for_resources=wait_for_resources + ) self._clients[key] = client return run, True @@ -491,6 +510,7 @@ async def start( client: ApifyClientAsync, start_run: Callable[[], Awaitable[Run]], abort_with_parent: bool = False, + wait_for_resources: bool | timedelta = False, ) -> tuple[Run, str]: """Start a run without a run name and record it. @@ -498,24 +518,98 @@ async def start( client: Client the run is started with. start_run: Starts the run of the Actor or task. abort_with_parent: Whether to abort the run when this Actor run is aborted. + wait_for_resources: Whether to retry the start while the API rejects it for the memory or concurrent-run + limit of the account, as in `find_or_start`. Returns: The run, and its key in the registry. Raises: - RuntimeError: If `abort_with_parent` is set and this Actor run is being aborted. No run is started. + RuntimeError: If `abort_with_parent` is set and this Actor run is being aborted, or the start would have + to wait for account resources then. No run is started. """ # The lock under a key of its own lets an abort of the child runs wait until the start is recorded. async with self._key_locks.setdefault(f'start:{next(self._start_ids)}', asyncio.Lock()): self._check_not_aborting('new child run', abort_with_parent=abort_with_parent) - async with self._start_in_flight('new child run'): - run = await start_run() + + async def record_run(run: Run) -> str: key = run_key(run.id) record = ChildRunRecord(run_id=run.id, status=run.status, abort_with_parent=abort_with_parent) await self._store(key, record) + return key + + run, key = await self._start_with_retries( + 'new child run', start_run=start_run, record_run=record_run, wait_for_resources=wait_for_resources + ) self._clients[key] = client return run, key + async def _start_with_retries( + self, + name: str, + *, + start_run: Callable[[], Awaitable[Run]], + record_run: Callable[[Run], Awaitable[str]], + wait_for_resources: bool | timedelta, + ) -> tuple[Run, str]: + """Start a run and record it, retrying the start while the account lacks the resources for the run. + + Between two attempts, the start is not in flight, so it counts neither toward the concurrency limit nor for + the wait before a reboot, metamorph or exit. + + Returns: + The run, and its key in the registry. + """ + deadline = None + if isinstance(wait_for_resources, timedelta): + deadline = asyncio.get_running_loop().time() + wait_for_resources.total_seconds() + + while True: + try: + async with self._start_in_flight(name): + run = await start_run() + key = await record_run(run) + 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(name, exc, deadline) + else: + return run, key + + async def _wait_for_resources(self, name: str, 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: + name: Name of the child run for the log and errors. + 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 aborted. + """ + delay: float = WAIT_FOR_RESOURCES_COOLDOWN_SECS + if deadline is not None: + remaining = deadline - asyncio.get_running_loop().time() + if remaining <= 0: + raise exc + delay = min(delay, remaining) + + if not self._abort_started.is_set(): + logger.info( + 'Not enough resources to start child run "%s", retrying in %.3g s: %s', name, delay, exc.message + ) + try: + await asyncio.wait_for(self._abort_started.wait(), delay) + except TimeoutError: + return + + # The parent is killed soon, and its abort waits for the lock of this start. + raise RuntimeError( + f'Child run "{name}" was not started, since this Actor run is being aborted and the account lacks the ' + 'resources for the run.' + ) from exc + def child_runs(self, default_client: ApifyClientAsync) -> list[ChildRun]: """Return the key, the record and a client of every recorded run, in recording order. @@ -561,6 +655,7 @@ async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: """ if self._abort_task is None: self._abort_task = asyncio.create_task(self._abort_runs_with_parent(client)) + self._abort_started.set() # The calls that wait for the concurrency limit hold the locks that the abort waits for, and give up now. self._capacity_changed.set() try: @@ -779,6 +874,7 @@ async def load(self) -> None: """ self._is_closed = False self._abort_task = None + self._abort_started.clear() self._starts_allowed.set() async with self._lock: try: diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 05fe1998..4f32c182 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 @@ -2300,6 +2300,185 @@ def test_concurrency_limit_needs_tracking() -> None: Actor(child_run_tracker=None, max_concurrent_child_runs=2) +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') + + +@pytest.mark.parametrize( + ('method', 'resource'), + [ + pytest.param('start', 'actor', id='start'), + pytest.param('start_task', 'task', id='start task'), + ], +) +@pytest.mark.parametrize( + 'wait_for_resources', + [ + pytest.param(False, id='false'), + pytest.param(True, id='true'), + pytest.param(timedelta(minutes=5), id='timedelta'), + ], +) +async def test_tracking_off_forwards_wait_for_resources_to_the_client( + apify_client_async_patcher: ApifyClientAsyncPatcher, + *, + method: str, + resource: str, + wait_for_resources: bool | timedelta, +) -> None: + """With child run tracking off, `wait_for_resources` goes to the client, which retries the start itself.""" + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + + async with Actor(child_run_tracker=None): + await getattr(Actor, method)('some-id', wait_for_resources=wait_for_resources) + + [(_, kwargs)] = apify_client_async_patcher.calls[resource]['start'] + assert kwargs['wait_for_resources'] == wait_for_resources + + +@pytest.mark.parametrize( + ('method', 'resource', 'run_name'), + [ + pytest.param('start', 'actor', None, id='start'), + pytest.param('call', 'actor', 'scrape-eu', id='named call'), + pytest.param('start_task', 'task', 'scrape-eu', id='named start task'), + pytest.param('call_task', 'task', None, 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, + run_name: str | None, + 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_SECS', 0.01) + 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.startswith('call') else {} + + async with Actor: + run = await getattr(Actor, method)('some-id', run_name=run_name, wait_for_resources=True, **kwargs) + [child_run] = 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_run.record.run_id == 'new-run' + + +@pytest.mark.parametrize( + ('wait_for_resources', 'error'), + [ + pytest.param(False, make_resource_limit_error(), id='resources not waited for'), + 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, 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', wait_for_resources=wait_for_resources) + child_runs = Actor.child_runs + + assert start_run.call_count == 1 + assert child_runs == [] + + +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_SECS', 0.005) + 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', 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 name 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', wait_for_resources=True)) + await asyncio.sleep(0.05) + 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) + child_runs = Actor.child_runs + + assert start_run.call_count == 1 + assert child_runs == [] + + +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', wait_for_resources=True)) + await asyncio.sleep(0.05) + 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_inherited_timeout_is_resolved_when_the_start_request_goes_out( apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch ) -> None: