diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 65f6ca4d..8bbc66ea 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -332,6 +332,7 @@ async def __aexit__( case the Actor: - Stops forwarding crawler status messages to the run status message. + - With a non-zero exit code, aborts the child runs started with `abort_with_parent`, waiting up to 10 s. - Emits the `EXIT` event. - Cancels periodic `PERSIST_STATE` events. - Sends a final `PERSIST_STATE` event. @@ -368,6 +369,9 @@ async def __aexit__( self.event_manager.off(event=Event.CRAWLER_STATUS, listener=self._forward_crawler_status) async def finalize() -> None: + if self.exit_code != 0 and self._child_run_registry.is_enabled: + await self._abort_child_runs() + if self.status_message is not None: try: async with self._status_message_lock: @@ -1158,7 +1162,7 @@ async def start( force_permission_level: ActorPermissionLevel | None = None, webhooks: list[Webhook] | None = None, run_name: str | None = None, - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, ) -> Run: """Run an Actor on the Apify platform. @@ -1196,16 +1200,20 @@ async def start( or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so their behavior and interface may change in future versions. - abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. - It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the - one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises - a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run - leaves the child running. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run receives the + `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero + code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. + A forced abort, a timeout, an out-of-memory kill or a normal finish of this Actor run leaves the child + running, and so does a child resurrected outside these methods, e.g. with `client.resurrect()`, since + its recorded status stays terminal. For a call with a `run_name` that returns a recorded run, `True` + 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`. Returns: Info about the started Actor run """ - self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent, token=token) if run_name is not None: _warn_child_runs_experimental() @@ -1355,7 +1363,7 @@ async def call( wait: timedelta | None = None, logger: logging.Logger | Literal['default'] | None = 'default', run_name: str | None = None, - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, ) -> Run: """Start an Actor on the Apify Platform and wait for it to finish before returning. @@ -1396,16 +1404,20 @@ async def call( or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so their behavior and interface may change in future versions. - abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. - It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the - one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises - a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run - leaves the child running. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run receives the + `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero + code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. + A forced abort, a timeout, an out-of-memory kill or a normal finish of this Actor run leaves the child + running, and so does a child resurrected outside these methods, e.g. with `client.resurrect()`, since + its recorded status stays terminal. For a call with a `run_name` that returns a recorded run, `True` + 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`. Returns: Info about the started Actor run. """ - self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent, token=token) if run_name is not None: _warn_child_runs_experimental() @@ -1452,19 +1464,23 @@ async def call( return run - def _check_child_run_options(self, *, run_name: str | None, abort_with_parent: bool) -> None: + def _check_child_run_options( + self, *, run_name: str | None, abort_with_parent: bool | None, token: str | None + ) -> None: """Validate the child run options of `start`, `call`, `start_task` and `call_task`. Raises: - ValueError: If an option needs child run tracking and it is off, or `abort_with_parent` lacks `run_name`. + ValueError: If an option needs child run tracking and it is off, or `abort_with_parent` comes with a + `token`. """ if not self._child_run_registry.is_enabled and (run_name is not None or abort_with_parent): raise ValueError( '`run_name` and `abort_with_parent` need child run tracking, which is turned off with ' '`child_run_tracker=None`.' ) - if abort_with_parent and run_name is None: - raise ValueError('`abort_with_parent` requires `run_name`.') + if abort_with_parent and token is not None: + # Tokens are not stored, so a later process of this Actor run could not abort the run. + raise ValueError('`abort_with_parent` cannot be combined with a custom `token`.') async def _start_child_run( self, @@ -1477,7 +1493,7 @@ async def _start_child_run( run_input: Any = None, content_type: str | None = None, options: dict[str, Any], - abort_with_parent: bool, + abort_with_parent: bool | None, ) -> tuple[Run, str | None, bool]: """Start a child run and record it, or return the run recorded under its explicit or implicit run name. @@ -1493,8 +1509,9 @@ async def _start_child_run( is_implicit = run_name is None and self.configuration.auto_memoize_child_runs if run_name is None and not is_implicit: - run = await start_run() - key = await self._child_run_registry.record(run, client=client) + run, key = await self._child_run_registry.start( + client=client, start_run=start_run, abort_with_parent=bool(abort_with_parent) + ) return run, key, True checksum = checksum_request( @@ -1588,7 +1605,7 @@ async def start_task( webhooks: list[Webhook] | None = None, token: str | None = None, run_name: str | None = None, - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, ) -> Run: """Start an Actor task on the Apify Platform. @@ -1626,16 +1643,20 @@ async def start_task( or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so their behavior and interface may change in future versions. - abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. - It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the - one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises - a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run - leaves the child running. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run receives the + `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero + code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. + A forced abort, a timeout, an out-of-memory kill or a normal finish of this Actor run leaves the child + running, and so does a child resurrected outside these methods, e.g. with `client.resurrect()`, since + its recorded status stays terminal. For a call with a `run_name` that returns a recorded run, `True` + 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`. Returns: Info about the started Actor run. """ - self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent, token=token) if run_name is not None: _warn_child_runs_experimental() @@ -1684,7 +1705,7 @@ async def call_task( logger: logging.Logger | Literal['default'] | None = 'default', token: str | None = None, run_name: str | None = None, - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, ) -> Run: """Start an Actor task on the Apify Platform and wait for it to finish before returning. @@ -1727,16 +1748,20 @@ async def call_task( or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so their behavior and interface may change in future versions. - abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. - It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the - one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises - a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run - leaves the child running. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run receives the + `ABORTING` event, or exits with a non-zero exit code (`Actor.fail()`, `Actor.exit()` with a non-zero + code, or an exception that leaves `async with Actor`), also after a migration, reboot or resurrection. + A forced abort, a timeout, an out-of-memory kill or a normal finish of this Actor run leaves the child + running, and so does a child resurrected outside these methods, e.g. with `client.resurrect()`, since + its recorded status stays terminal. For a call with a `run_name` that returns a recorded run, `True` + 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`. Returns: Info about the started Actor run. """ - self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent, token=token) if run_name is not None: _warn_child_runs_experimental() diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index a2aa3112..dee9d442 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -2,6 +2,7 @@ import asyncio import hashlib +import itertools import json from abc import ABC, abstractmethod from logging import getLogger @@ -36,6 +37,9 @@ TERMINAL_RUN_STATUSES = frozenset({'SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED-OUT'}) """Statuses of a run that is finished. A run in any other status is active.""" +ABORT_WITH_PARENT_TIMEOUT_SECS = 10 +"""How long aborting the child runs with the parent is waited for.""" + _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.""" @@ -347,8 +351,9 @@ def __init__(self, tracker: ChildRunTracker | None, *, warn_on_excessive_runs: b """Serializes `find_or_start` per key. A lock is dropped once no call under its key holds it.""" self._clients: dict[str, ApifyClientAsync] = {} """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._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._start_ids = itertools.count() self._warned_excessive_runs = False @property @@ -363,7 +368,7 @@ async def find_or_start( checksum: str, client: ApifyClientAsync, start_run: Callable[[], Awaitable[Run]], - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, ) -> tuple[Run, bool]: """Return the run recorded under `key`, or start one when there is none. @@ -376,24 +381,17 @@ async def find_or_start( started with the same request. client: Client used to look up the recorded run. start_run: Starts a new run of the Actor or task. - abort_with_parent: Whether to abort the run when this Actor run is gracefully aborted. It replaces the value - recorded under `key`. + 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`. 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 `abort_with_parent` is set and this Actor run is being gracefully aborted. No run is - started or returned. + RuntimeError: If a new run with `abort_with_parent` would start while this Actor run is being aborted. """ async with self._key_locks.setdefault(key, asyncio.Lock()): - if abort_with_parent and self._parent_aborting: - raise RuntimeError( - f'Child run "{key}" with `abort_with_parent` was not started, since this Actor run is being ' - 'aborted.' - ) - record = self._get_records().get(key) if record is not None: @@ -407,9 +405,10 @@ async def find_or_start( if run is not None: logger.info('Reattaching to child run "%s"', key, extra={'run_id': run.id, 'status': run.status}) - updated_record = record.model_copy( - update={'status': run.status, 'abort_with_parent': abort_with_parent} - ) + update: dict[str, Any] = {'status': run.status} + if abort_with_parent is not None: + update['abort_with_parent'] = abort_with_parent + updated_record = record.model_copy(update=update) if updated_record != record: await self._store(key, updated_record) self._clients[key] = client @@ -421,31 +420,48 @@ async def find_or_start( extra={'run_id': record.run_id}, ) + self._check_not_aborting(key, abort_with_parent=bool(abort_with_parent)) run = await start_run() new_record = ChildRunRecord( run_id=run.id, status=run.status, - abort_with_parent=abort_with_parent, + abort_with_parent=bool(abort_with_parent), checksum=checksum, ) await self._store(key, new_record) self._clients[key] = client return run, True - async def record(self, run: Run, *, client: ApifyClientAsync) -> str: - """Record a run started without a run name. + async def start( + self, + *, + client: ApifyClientAsync, + start_run: Callable[[], Awaitable[Run]], + abort_with_parent: bool = False, + ) -> tuple[Run, str]: + """Start a run without a run name and record it. Args: - run: The run as returned by the start request. - client: Client the run was started with. + 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. Returns: - Key of the run in the registry. + 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. """ - key = run_key(run.id) - await self._store(key, ChildRunRecord(run_id=run.id, status=run.status)) - self._clients[key] = client - return key + # 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) + run = await start_run() + key = run_key(run.id) + await self._store( + key, ChildRunRecord(run_id=run.id, status=run.status, abort_with_parent=abort_with_parent) + ) + self._clients[key] = client + return run, key def child_runs(self, default_client: ApifyClientAsync) -> list[ChildRun]: """Return the key, the record and a client of every recorded run, in recording order. @@ -476,40 +492,64 @@ async def update(self, key: str, run: Run) -> None: await self._store(key, record.model_copy(update={'status': run.status})) async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: - """Gracefully abort every recorded run marked `abort_with_parent`, and refuse to start any more of them. + """Abort every run marked `abort_with_parent`, and refuse to start any more of them. - Each run gets one abort request, all in parallel. The platform leaves a run that already finished as it is. A - failure to abort one run is logged and does not stop the others. A run whose start is in flight is aborted once - the start records it. + Each recorded run with an active status gets one graceful abort request, all in parallel, including the runs + recorded by earlier processes of this Actor run and the starts in flight once they are recorded. A failure to + abort one run is logged and does not stop the others. Waiting stops after `ABORT_WITH_PARENT_TIMEOUT_SECS`. + A later call waits for the abort that the first call began. Args: 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 - # The event can arrive before the Actor has loaded the registry. + if self._abort_task is None: + self._abort_task = asyncio.create_task(self._abort_runs_with_parent(client)) + try: + await asyncio.wait_for(asyncio.shield(self._abort_task), ABORT_WITH_PARENT_TIMEOUT_SECS) + except TimeoutError: + logger.warning( + 'Stopped waiting for the child runs to be aborted with the parent after %d s', + ABORT_WITH_PARENT_TIMEOUT_SECS, + ) + + async def _abort_runs_with_parent(self, default_client: ApifyClientAsync) -> None: + # The abort can begin before the Actor has loaded the registry. await self._loaded.wait() - # The Actor failed to load the registry, so it knows no runs to abort. + # Without the registry, e.g. when the Actor failed to load it, there are no known runs to abort. if self._records is None: return - # Keys with a start in flight are not recorded yet, so their locks are awaited too. - await asyncio.gather(*(self._abort(key, client) for key in {*self._records, *self._key_locks})) - - async def _abort(self, key: str, default_client: ApifyClientAsync) -> None: - async with self._key_locks.setdefault(key, asyncio.Lock()): - record = self._get_records().get(key) - if record is None or not record.abort_with_parent: - return - run_client = self._clients.get(key, default_client).run(record.run_id) - try: - run = await run_client.abort(gracefully=True) - except NotFoundError: - logger.debug('Child run "%s" no longer exists', key, extra={'run_id': record.run_id}) - except Exception: - logger.exception('Failed to abort child run "%s"', key, extra={'run_id': record.run_id}) - else: - if run.status in _ABORTED_STATUSES: - logger.info('Aborted child run "%s" with the parent', key, extra={'run_id': record.run_id}) + # The starts in flight hold their locks until their runs are recorded. + await asyncio.gather(*(self._wait_for_lock(lock) for lock in list(self._key_locks.values()))) + marked = [ + (key, record) + for key, record in self._records.items() + if record.abort_with_parent and record.status not in TERMINAL_RUN_STATUSES + ] + await asyncio.gather(*(self._abort(key, record, default_client) for key, record in marked)) + + @staticmethod + async def _wait_for_lock(lock: asyncio.Lock) -> None: + async with lock: + pass + + async def _abort(self, key: str, record: ChildRunRecord, default_client: ApifyClientAsync) -> None: + run_client = self._clients.get(key, default_client).run(record.run_id) + try: + run = await run_client.abort(gracefully=True) + except NotFoundError: + logger.debug('Child run "%s" no longer exists', key, extra={'run_id': record.run_id}) + except Exception: + logger.exception('Failed to abort child run "%s"', key, extra={'run_id': record.run_id}) + else: + if run.status in _ABORTED_STATUSES: + logger.info('Aborted child run "%s" with the parent', key, extra={'run_id': record.run_id}) + + def _check_not_aborting(self, name: str, *, abort_with_parent: bool) -> None: + if abort_with_parent and self._abort_task is not None: + raise RuntimeError( + f'Child run "{name}" with `abort_with_parent` was not started, since this Actor run is being aborted.' + ) async def load(self) -> None: """Read the records through the tracker, replacing any read before. Does nothing with tracking off.""" diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 092d148b..c52a738c 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1089,21 +1089,19 @@ async def test_child_runs_keeps_client_of_name_after_failed_lookup( pytest.param('call_task', id='call task'), ], ) -async def test_abort_with_parent_requires_run_name( +async def test_abort_with_parent_rejects_custom_token( apify_client_async_patcher: ApifyClientAsyncPatcher, method: str ) -> None: - """`abort_with_parent` without a `run_name` raises before any run is started.""" + """`abort_with_parent` with a custom `token` raises before any run is started, since tokens are not stored.""" for resource in ('actor', 'task'): apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('actor', 'call', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - with pytest.raises(ValueError, match='requires `run_name`'): - await getattr(Actor, method)('some-id', abort_with_parent=True) + with pytest.raises(ValueError, match='custom `token`'): + await getattr(Actor, method)('some-id', abort_with_parent=True, token='other-token') for resource in ('actor', 'task'): assert apify_client_async_patcher.calls[resource]['start'] == [] - assert apify_client_async_patcher.calls['actor']['call'] == [] async def test_named_start_records_abort_with_parent(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -1327,10 +1325,11 @@ async def start_run() -> Run: client.run.return_value.abort.assert_awaited_once_with(gracefully=True) -async def test_named_start_queued_behind_a_start_in_flight_raises_once_aborting() -> None: - """A named start waiting on its name while the parent is aborted raises, and the run in flight is aborted.""" +async def test_named_start_queued_behind_a_start_in_flight_returns_its_run_once_aborting() -> None: + """A named start waiting on its name while the parent is aborted gets the run in flight, which is aborted.""" client = Mock() client.run.return_value.abort = AsyncMock(return_value=make_run('new-run', 'ABORTING')) + client.run.return_value.get = AsyncMock(return_value=make_run('new-run', 'ABORTING')) started = asyncio.Event() release = asyncio.Event() @@ -1354,9 +1353,9 @@ async def start_run() -> Run: await asyncio.sleep(0) release.set() await asyncio.gather(first_start, abort_task) - with pytest.raises(RuntimeError, match='being aborted'): - await queued_start + run, is_new = await queued_start + assert (run.id, is_new) == ('new-run', False) queued_start_run.assert_not_awaited() client.run.return_value.abort.assert_awaited_once_with(gracefully=True) @@ -1391,10 +1390,10 @@ async def test_named_start_with_abort_with_parent_raises_once_aborting( assert stored is None -async def test_named_call_once_aborting_does_not_resurrect_the_aborted_child( +async def test_named_call_once_aborting_returns_the_aborted_child( apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager ) -> None: - """After `ABORTING`, a named call with `abort_with_parent` under a recorded name leaves the aborted child alone.""" + """After `ABORTING`, a named call under a recorded name returns the aborted child without starting a run.""" apify_client_async_patcher.patch('run', 'abort', return_value=make_run('old-run', 'ABORTING')) apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTED')) apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) @@ -1406,9 +1405,9 @@ async def test_named_call_once_aborting_does_not_resurrect_the_aborted_child( await Actor._child_run_registry.load() apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) await apify_event_manager.wait_for_all_listeners_to_complete() - with pytest.raises(RuntimeError, match='being aborted'): - await Actor.call('some-actor', run_name='scrape-eu', abort_with_parent=True) + run = await Actor.call('some-actor', run_name='scrape-eu', abort_with_parent=True) + assert run.status == 'ABORTED' assert len(apify_client_async_patcher.calls['run']['abort']) == 1 assert apify_client_async_patcher.calls['run']['resurrect'] == [] assert apify_client_async_patcher.calls['actor']['start'] == [] @@ -1776,3 +1775,153 @@ async def test_auto_memoize_without_tracking_fails_init(monkeypatch: pytest.Monk with pytest.raises(ValueError, match='auto_memoize_child_runs'): await Actor(child_run_tracker=None).init() + + +async def test_unnamed_run_with_abort_with_parent_is_aborted_on_aborting( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """A run started without a name and with `abort_with_parent` is recorded with the flag and aborted on `ABORTING`.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'abort', return_value=make_run('new-run', 'ABORTING')) + + async with Actor: + await Actor.start('some-actor', abort_with_parent=True) + [child_run] = Actor.child_runs + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + with pytest.raises(RuntimeError, match='being aborted'): + await Actor.start('some-actor', abort_with_parent=True) + + assert child_run.record.abort_with_parent is True + assert len(apify_client_async_patcher.calls['run']['abort']) == 1 + assert len(apify_client_async_patcher.calls['actor']['start']) == 1 + + +@pytest.mark.parametrize( + 'exit_kind', + [ + pytest.param('fail', id='fail'), + pytest.param('exit with non-zero code', id='exit with non-zero code'), + pytest.param('exception', id='exception'), + ], +) +async def test_non_zero_exit_aborts_marked_child_runs( + apify_client_async_patcher: ApifyClientAsyncPatcher, exit_kind: str +) -> None: + """A non-zero exit of the parent aborts the marked child runs, also without the `ABORTING` event.""" + runs = iter([make_run('marked-run', 'READY'), make_run('other-run', 'READY')]) + apify_client_async_patcher.patch('actor', 'start', replacement_method=lambda *_args, **_kwargs: next(runs)) + apify_client_async_patcher.patch('run', 'abort', return_value=make_run('marked-run', 'ABORTING')) + + actor = Actor(exit_process=False) + await actor.init() + await actor.start('some-actor', abort_with_parent=True) + await actor.start('some-actor') + if exit_kind == 'fail': + await actor.fail() + elif exit_kind == 'exit with non-zero code': + await actor.exit(exit_code=3) + else: + await actor.__aexit__(RuntimeError, RuntimeError('boom'), None) + + [(abort_args, abort_kwargs)] = apify_client_async_patcher.calls['run']['abort'] + assert abort_args[0].resource_id == 'marked-run' + assert abort_kwargs == {'gracefully': True} + + +async def test_clean_exit_leaves_marked_child_runs(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A clean exit of the parent does not abort the child runs marked `abort_with_parent`.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'abort', return_value=make_run('new-run', 'ABORTING')) + + async with Actor: + await Actor.start('some-actor', abort_with_parent=True) + + assert apify_client_async_patcher.calls['run']['abort'] == [] + + +async def test_abort_skips_runs_with_terminal_recorded_status( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """Only the marked runs whose recorded status is active get an abort request.""" + apify_client_async_patcher.patch('run', 'abort', return_value=make_run('running-run', 'ABORTING')) + records = { + 'run:running-run': {'runId': 'running-run', 'status': 'RUNNING', 'abortWithParent': True}, + 'run:done-run': {'runId': 'done-run', 'status': 'SUCCEEDED', 'abortWithParent': True}, + } + + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(runs=records)) + + actor = Actor(exit_process=False) + await actor.init() + await actor.fail() + + [(abort_args, _)] = apify_client_async_patcher.calls['run']['abort'] + assert abort_args[0].resource_id == 'running-run' + + +async def test_aborting_and_failing_abort_child_runs_once( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """The `ABORTING` event and the non-zero exit that follows it send one abort request per child run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'abort', return_value=make_run('new-run', 'ABORTING')) + + actor = Actor(exit_process=False) + await actor.init() + await actor.start('some-actor', abort_with_parent=True) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + await actor.fail() + + assert len(apify_client_async_patcher.calls['run']['abort']) == 1 + + +async def test_exit_stops_waiting_for_slow_child_run_abort( + apify_client_async_patcher: ApifyClientAsyncPatcher, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A non-zero exit waits for the abort of the child runs only up to the time limit, then logs a warning.""" + monkeypatch.setattr(_child_runs, 'ABORT_WITH_PARENT_TIMEOUT_SECS', 0.1) + never_finishes = asyncio.Event() + + async def abort(*_args: Any, **_kwargs: Any) -> Run: + await never_finishes.wait() + return make_run('new-run', 'ABORTING') + + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'abort', replacement_method=abort) + + actor = Actor(exit_process=False) + await actor.init() + await actor.start('some-actor', abort_with_parent=True) + await asyncio.wait_for(actor.fail(), timeout=10) + + assert 'Stopped waiting for the child runs to be aborted with the parent' in caplog.text + + +@pytest.mark.parametrize( + ('call_value', 'recorded_value'), + [ + pytest.param(None, True, id='none keeps'), + pytest.param(False, False, id='false replaces'), + ], +) +async def test_named_call_abort_with_parent_none_keeps_recorded_value( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, call_value: bool | None, recorded_value: bool +) -> None: + """A named call returning a recorded run keeps its `abortWithParent` with `None` and replaces it otherwise.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'RUNNING')) + + async with Actor: + kvs = await Actor.open_key_value_store() + record = stored_record('old-run', 'RUNNING', abort_with_parent=True) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'scrape-eu': record})) + await Actor._child_run_registry.load() + await Actor.start('some-actor', run_name='scrape-eu', abort_with_parent=call_value) + [child_run] = Actor.child_runs + + assert child_run.record.abort_with_parent is recorded_value