diff --git a/.rules.md b/.rules.md index a91d9d86..e6edd61d 100644 --- a/.rules.md +++ b/.rules.md @@ -22,7 +22,7 @@ Don't introduce a shared Pydantic base model to centralize `model_config`. Each - **`Actor`** (`_actor.py`) is a `lazy-object-proxy` wrapping `_ActorType`. It works both as a class (`Actor.is_at_home()`) and as a context manager (`async with Actor:`); on `__aenter__` the proxy's `__wrapped__` is replaced with the active `_ActorType` instance. - **`Configuration`** (`_configuration.py`) extends Crawlee's `Configuration` and is populated from `APIFY_*` environment variables. -- **Named child runs** (`_child_runs.py`) — runs started with `run_name` are persisted in the default key-value store so they can be reattached after a migration or resurrection; exposed through `Actor.child_runs`. +- **Child runs** (`_child_runs.py`) — runs started with `run_name`, and with `Configuration.persist_unnamed_child_runs` also the ones without it, are recorded in the default key-value store under `APIFY_ACTOR_CHILD_RUNS`, so a later process of the parent (after a migration, reboot, or resurrection) gets them back; exposed through `Actor.child_runs`. - **Storage clients** (`storage_clients/`) implement Crawlee's storage client interface: `ApifyStorageClient` talks to the Apify API (separate sub-clients for single vs. shared request queues), `FileSystemStorageClient` adds Apify-specific key-value store behavior, and `SmartApifyStorageClient` delegates to the cloud client on the platform and to the local one elsewhere. - **Events** — `ApifyEventManager` receives platform events over a WebSocket. - **Errors** — `apify.errors` only re-exports the exceptions from `apify_client.errors`; the SDK defines no error classes of its own, and API calls raise the client exceptions unchanged. diff --git a/src/apify/__init__.py b/src/apify/__init__.py index 76e7a382..024321f6 100644 --- a/src/apify/__init__.py +++ b/src/apify/__init__.py @@ -13,6 +13,7 @@ ) from apify._actor import Actor +from apify._child_runs import ChildRun, ChildRunRecord, ChildRuns from apify._configuration import Configuration from apify._consts import ActorEnvVars, ApifyEnvVars from apify._proxy_configuration import ProxyConfiguration, ProxyInfo @@ -26,6 +27,9 @@ 'ActorEnvVars', 'ActorEventTypes', 'ApifyEnvVars', + 'ChildRun', + 'ChildRunRecord', + 'ChildRuns', 'Configuration', 'Event', 'EventAbortingData', diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 3e650c05..926da1c3 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -37,7 +37,13 @@ ChargingManagerImplementation, charge_lock_if_charging, ) -from apify._child_runs import ChildRunRegistry +from apify._child_runs import ( + TERMINAL_RUN_STATUSES, + ChildRunKey, + ChildRunRegistry, + checksum_request, + checksum_run_options, +) from apify._configuration import Configuration from apify._consts import ( EVENT_LISTENERS_TIMEOUT, @@ -69,6 +75,7 @@ from crawlee._types import JsonSerializable from crawlee.proxy_configuration import _NewUrlFunction + from apify._child_runs import ChildRuns from apify._webhook import Webhook MainReturnType = TypeVar('MainReturnType') @@ -78,8 +85,8 @@ def _warn_child_runs_experimental() -> None: warnings.warn( - 'Named child runs (`run_name`, `abort_with_parent` and `Actor.child_runs`) are experimental. Their behavior ' - 'and interface may change in future versions.', + 'Tracked child runs (`run_name`, `persist_unnamed_child_runs`, `abort_with_parent`, `resurrect_with_parent` ' + 'and `Actor.child_runs`) are experimental. Their behavior and interface may change in future versions.', UserWarning, # This helper, the SDK method, and its `ensure_context` wrapper sit between the warning and the caller. stacklevel=4, @@ -181,7 +188,7 @@ def __init__( # Keep track of all used state stores to persist their values on exit self._use_state_stores: set[str | None] = set() - self._child_run_registry = ChildRunRegistry(self.open_key_value_store) + self._child_run_registry = ChildRunRegistry(self.open_key_value_store, is_parent_aborting=self._is_run_aborting) self._internal_listeners = ExitStack() """Removes the listeners the Actor registered on the event manager, when the Actor leaves its context.""" @@ -206,7 +213,7 @@ async def __aenter__(self) -> Self: - Sets up local or cloud storage clients depending on whether the Actor runs locally or on the Apify platform. - Configures the event manager and starts periodic state persistence. - Initializes the charging manager for handling charging events. - - Loads the named child runs recorded by an earlier attempt of this Actor run. + - Loads the child runs recorded by an earlier process of this Actor run. - On the Apify platform, forwards the status messages of Crawlee crawlers to the run status message. - Configures logging after all core services are registered. @@ -253,6 +260,8 @@ async def __aenter__(self) -> Self: ) self._internal_listeners.callback(remove_listener) rollback.callback(self._internal_listeners.close) + # An `ABORTING` listener that already runs waits for the registry, which a failed init never loads. + rollback.callback(self._child_run_registry.stop_waiting_for_load) self.log.debug('Event manager initialized') # Initialize the charging manager. @@ -298,6 +307,7 @@ async def __aexit__( - Stops forwarding crawler status messages to the run status message. - Emits the `EXIT` event. + - Waits for the abort of the child runs marked `abort_with_parent`, if this Actor run is being aborted. - Cancels periodic `PERSIST_STATE` events. - Sends a final `PERSIST_STATE` event. - Waits for all event listeners to finish. @@ -345,6 +355,12 @@ async def finalize() -> None: # Sleep for a bit so that the listeners have a chance to trigger await asyncio.sleep(0.1) + # The abort of the child runs has its own time limit, apart from the one for the event listeners. + try: + await self._child_run_registry.wait_for_abort() + except Exception: + self.log.exception('Failed to abort the child runs with the Actor run') + if self._event_listeners_timeout: await self.event_manager.wait_for_all_listeners_to_complete(timeout=self._event_listeners_timeout) @@ -442,25 +458,29 @@ def apify_client(self) -> ApifyClientAsync: @property @_ensure_context - def child_runs(self) -> dict[str, RunClientAsync]: - """Clients for the named child runs of this Actor run, keyed by the run name. + def child_runs(self) -> ChildRuns: + """The child runs of this Actor run, with the record and a client for each of them. Every run started by `Actor.start`, `Actor.call`, `Actor.start_task` or `Actor.call_task` with a `run_name` is - included, even one started before a migration or resurrection of this Actor run. Runs started without a - `run_name` are not tracked. Each client points to the current run under its name: + listed in `named` under that name, even one started by an earlier process of this Actor run, before + a migration, reboot or resurrection. Runs started without a `run_name` are listed in `unnamed` when + `Configuration.persist_unnamed_child_runs` is on, and are not tracked when it is off. Each entry holds + the stored `record` and a `client` for the run: ```python - run = await Actor.child_runs['my-child'].wait_for_finish() + record, client = Actor.child_runs.named['my-child'] + run = await client.wait_for_finish() ``` - A run started or reattached with a custom `token` since the last migration or resurrection of this Actor run - uses that token. Any other run uses the default client. + `record.status` is the last status this Actor run observed, so it can be out of date, and `client.get()` + returns the current run. A run started or returned with a custom `token` in this process has a client with + that token. Tokens are not stored, so a run recorded by an earlier process has the default client. Warning: This is an experimental feature. The behavior and interface may change in future versions. """ _warn_child_runs_experimental() - return self._child_run_registry.run_clients(self.apify_client) + return self._child_run_registry.child_runs(self.apify_client) @cached_property def configuration(self) -> Configuration: @@ -1110,7 +1130,8 @@ 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, + resurrect_with_parent: bool | None = None, ) -> Run: """Run an Actor on the Apify platform. @@ -1141,25 +1162,41 @@ async def start( the Actor run which can be used to receive a notification, e.g. when the Actor finished or failed. If you already have a webhook set up for the Actor or task, you do not have to add it again here. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the - default key-value store, so after a migration or resurrection of this Actor the same call reattaches - to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. 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 the value is recorded under it, replacing the one from an earlier - call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and - starts, resurrects or reattaches no run. A hard abort, a timeout or a crash of this Actor run leaves - the child running. + default key-value store, so a later call with the same name returns the recorded run, also after a + migration, reboot or resurrection of this Actor. The recorded run is returned in whatever status it is + in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer + exists. Using `run_name` for a different Actor, task, input or run options raises a `ValueError`, and an + input that is not sent as JSON raises a `TypeError`. Without a `run_name`, the run is recorded only when + `Configuration.persist_unnamed_child_runs` is on, and then an identical call returns the recorded run. + Tracked child runs are experimental, so their behavior and interface may change in future versions. + abort_with_parent: Whether the child run is gracefully aborted when this Actor run is gracefully aborted. + `True` or `False` is recorded with the run and replaces the value of an earlier call. `None` keeps the + recorded value, which is `False` for a new run. Without a `run_name` it needs + `Configuration.persist_unnamed_child_runs`. Once this Actor run is being gracefully aborted, a call that + would start a new run with it raises a `RuntimeError`. A hard abort, a timeout or a crash of this Actor + run leaves the child running. + resurrect_with_parent: Whether this call resurrects the child run after it was aborted with this Actor run + through `abort_with_parent`. The call resurrects the run in a process of this Actor run that started + 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`. Returns: Info about the started Actor run """ - if abort_with_parent and run_name is None: - raise ValueError('`abort_with_parent` requires `run_name`, since only named child runs are tracked.') + is_tracked = run_name is not None or self.configuration.persist_unnamed_child_runs + if abort_with_parent and not is_tracked: + raise ValueError( + '`abort_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since other ' + 'child runs are not tracked.' + ) + if resurrect_with_parent and not is_tracked: + raise ValueError( + '`resurrect_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since ' + 'other child runs are not tracked.' + ) - if run_name is not None: + if is_tracked: _warn_child_runs_experimental() if max_items is not None: @@ -1182,22 +1219,28 @@ async def start( webhooks=to_client_representations(webhooks), ) - if run_name is None: + if not is_tracked: return await start_run() - run, _ = await self._find_or_start_child_run( + _, run, _ = await self._find_or_start_child_run( run_name, actor_id=actor_id, run_input=run_input, + content_type=content_type, client=client, start_run=start_run, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - timeout=timeout, + options=checksum_run_options( + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + timeout=timeout, + force_permission_level=force_permission_level, + webhooks=to_client_representations(webhooks), + ), abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, ) return run @@ -1312,7 +1355,8 @@ 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, + resurrect_with_parent: bool | None = None, ) -> Run: """Start an Actor on the Apify Platform and wait for it to finish before returning. @@ -1346,25 +1390,41 @@ async def call( default logger will be used. Setting `None` will disable any log propagation. Passing custom logger will redirect logs to the provided logger. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the - default key-value store, so after a migration or resurrection of this Actor the same call reattaches - to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. 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 the value is recorded under it, replacing the one from an earlier - call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and - starts, resurrects or reattaches no run. A hard abort, a timeout or a crash of this Actor run leaves - the child running. + default key-value store, so a later call with the same name returns the recorded run, also after a + migration, reboot or resurrection of this Actor. The recorded run is returned in whatever status it is + in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer + exists. Using `run_name` for a different Actor, task, input or run options raises a `ValueError`, and an + input that is not sent as JSON raises a `TypeError`. Without a `run_name`, the run is recorded only when + `Configuration.persist_unnamed_child_runs` is on, and then an identical call returns the recorded run. + Tracked child runs are experimental, so their behavior and interface may change in future versions. + abort_with_parent: Whether the child run is gracefully aborted when this Actor run is gracefully aborted. + `True` or `False` is recorded with the run and replaces the value of an earlier call. `None` keeps the + recorded value, which is `False` for a new run. Without a `run_name` it needs + `Configuration.persist_unnamed_child_runs`. Once this Actor run is being gracefully aborted, a call that + would start a new run with it raises a `RuntimeError`. A hard abort, a timeout or a crash of this Actor + run leaves the child running. + resurrect_with_parent: Whether this call resurrects the child run after it was aborted with this Actor run + through `abort_with_parent`. The call resurrects the run in a process of this Actor run that started + 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`. Returns: Info about the started Actor run. """ - if abort_with_parent and run_name is None: - raise ValueError('`abort_with_parent` requires `run_name`, since only named child runs are tracked.') + is_tracked = run_name is not None or self.configuration.persist_unnamed_child_runs + if abort_with_parent and not is_tracked: + raise ValueError( + '`abort_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since other ' + 'child runs are not tracked.' + ) + if resurrect_with_parent and not is_tracked: + raise ValueError( + '`resurrect_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since ' + 'other child runs are not tracked.' + ) - if run_name is not None: + if is_tracked: _warn_child_runs_experimental() if max_items is not None: @@ -1374,7 +1434,7 @@ async def call( actor_client = client.actor(actor_id) - if run_name is None: + if not is_tracked: run = await actor_client.call( run_input=run_input, content_type=content_type, @@ -1390,10 +1450,11 @@ async def call( logger=logger, ) else: - started_run, is_new = await self._find_or_start_child_run( + key, started_run, is_new = await self._find_or_start_child_run( run_name, actor_id=actor_id, run_input=run_input, + content_type=content_type, client=client, start_run=partial( actor_client.start, @@ -1408,17 +1469,22 @@ async def call( force_permission_level=force_permission_level, webhooks=to_client_representations(webhooks), ), - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - timeout=timeout, + options=checksum_run_options( + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + timeout=timeout, + force_permission_level=force_permission_level, + webhooks=to_client_representations(webhooks), + ), abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, ) - # The earlier attempt of this call already streamed the log of a reattached or resurrected run. + # 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( - run_name, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new + key, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new ) if run is None: @@ -1428,45 +1494,50 @@ async def call( async def _find_or_start_child_run( self, - name: str, + run_name: str | None, *, actor_id: str | None = None, task_id: str | None = None, run_input: Any, + content_type: str | None = None, + options: dict[str, Any], client: ApifyClientAsync, start_run: Callable[[], Awaitable[Run]], - build: str | None, - max_items: int | None, - max_total_charge_usd: Decimal | None, - restart_on_error: bool | None, - memory_mbytes: int | None, - timeout: timedelta | Literal['inherit'] | None, - abort_with_parent: bool, - ) -> tuple[Run, bool]: - return await self._child_run_registry.find_or_start( - name, + abort_with_parent: bool | None, + resurrect_with_parent: bool | None, + ) -> tuple[ChildRunKey, Run, bool]: + checksum = checksum_request( actor_id=actor_id, task_id=task_id, run_input=run_input, + content_type=content_type, + options=options, + ) + key = ChildRunKey.from_request(run_name, checksum) + run, is_new = await self._child_run_registry.find_or_start( + key, + checksum=checksum, client=client, start_run=start_run, - resurrect_run=lambda run_id: client.run(run_id).resurrect( - build=build, - memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - ), abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, ) + return key, run, is_new + + async def _is_run_aborting(self) -> bool: + """Ask the platform whether this Actor run is being gracefully aborted.""" + run_id = self.configuration.actor_run_id + if not self.is_at_home() or not run_id: + return False + run = await self.apify_client.run(run_id).get() + return run is not None and run.status == 'ABORTING' async def _abort_child_runs(self) -> None: await self._child_run_registry.abort_runs_with_parent(self.apify_client) async def _wait_for_child_run( self, - name: str, + key: ChildRunKey, run_client: RunClientAsync, run: Run, *, @@ -1474,7 +1545,7 @@ async def _wait_for_child_run( logger: logging.Logger | Literal['default'] | None, from_start: bool, ) -> Run | None: - if run.status == 'SUCCEEDED': + if run.status in TERMINAL_RUN_STATUSES: return run if not logger: @@ -1488,7 +1559,7 @@ async def _wait_for_child_run( finished_run = await run_client.wait_for_finish(wait_duration=wait) if finished_run is not None: - await self._child_run_registry.update(name, finished_run) + await self._child_run_registry.update(key, finished_run) return finished_run @_ensure_context @@ -1506,7 +1577,8 @@ 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, + resurrect_with_parent: bool | None = None, ) -> Run: """Start an Actor task on the Apify Platform. @@ -1537,25 +1609,41 @@ async def start_task( be used to receive a notification, e.g. when the Actor finished or failed. If you already have a webhook set up for the Actor, you do not have to add it again here. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the - default key-value store, so after a migration or resurrection of this Actor the same call reattaches - to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. 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 the value is recorded under it, replacing the one from an earlier - call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and - starts, resurrects or reattaches no run. A hard abort, a timeout or a crash of this Actor run leaves - the child running. + default key-value store, so a later call with the same name returns the recorded run, also after a + migration, reboot or resurrection of this Actor. The recorded run is returned in whatever status it is + in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer + exists. Using `run_name` for a different Actor, task, input or run options raises a `ValueError`, and an + input that is not sent as JSON raises a `TypeError`. Without a `run_name`, the run is recorded only when + `Configuration.persist_unnamed_child_runs` is on, and then an identical call returns the recorded run. + Tracked child runs are experimental, so their behavior and interface may change in future versions. + abort_with_parent: Whether the child run is gracefully aborted when this Actor run is gracefully aborted. + `True` or `False` is recorded with the run and replaces the value of an earlier call. `None` keeps the + recorded value, which is `False` for a new run. Without a `run_name` it needs + `Configuration.persist_unnamed_child_runs`. Once this Actor run is being gracefully aborted, a call that + would start a new run with it raises a `RuntimeError`. A hard abort, a timeout or a crash of this Actor + run leaves the child running. + resurrect_with_parent: Whether this call resurrects the child run after it was aborted with this Actor run + through `abort_with_parent`. The call resurrects the run in a process of this Actor run that started + 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`. Returns: Info about the started Actor run. """ - if abort_with_parent and run_name is None: - raise ValueError('`abort_with_parent` requires `run_name`, since only named child runs are tracked.') + is_tracked = run_name is not None or self.configuration.persist_unnamed_child_runs + if abort_with_parent and not is_tracked: + raise ValueError( + '`abort_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since other ' + 'child runs are not tracked.' + ) + if resurrect_with_parent and not is_tracked: + raise ValueError( + '`resurrect_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since ' + 'other child runs are not tracked.' + ) - if run_name is not None: + if is_tracked: _warn_child_runs_experimental() if max_items is not None: @@ -1575,22 +1663,26 @@ async def start_task( webhooks=to_client_representations(webhooks), ) - if run_name is None: + if not is_tracked: return await start_run() - run, _ = await self._find_or_start_child_run( + _, run, _ = await self._find_or_start_child_run( run_name, task_id=task_id, run_input=task_input, client=client, start_run=start_run, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - timeout=timeout, + options=checksum_run_options( + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + timeout=timeout, + webhooks=to_client_representations(webhooks), + ), abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, ) return run @@ -1610,7 +1702,8 @@ async def call_task( wait: timedelta | None = None, token: str | None = None, run_name: str | None = None, - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, + resurrect_with_parent: bool | None = None, ) -> Run: """Start an Actor task on the Apify Platform and wait for it to finish before returning. @@ -1641,25 +1734,41 @@ async def call_task( a webhook set up for the Actor, you do not have to add it again here. wait: The maximum time the server waits for the run to finish. If not provided, waits indefinitely. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the - default key-value store, so after a migration or resurrection of this Actor the same call reattaches - to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is - resurrected, and a new run is started only when nothing is recorded under the name, or the recorded - run `FAILED` or no longer exists. Using `run_name` to attach to a run of a different Actor, task or - with a different input raises a `ValueError`. 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 the value is recorded under it, replacing the one from an earlier - call. Once this Actor run is being gracefully aborted, a call with it raises a `RuntimeError` and - starts, resurrects or reattaches no run. A hard abort, a timeout or a crash of this Actor run leaves - the child running. + default key-value store, so a later call with the same name returns the recorded run, also after a + migration, reboot or resurrection of this Actor. The recorded run is returned in whatever status it is + in, and a new run is started only when nothing is recorded under the name, or the recorded run no longer + exists. Using `run_name` for a different Actor, task, input or run options raises a `ValueError`, and an + input that is not sent as JSON raises a `TypeError`. Without a `run_name`, the run is recorded only when + `Configuration.persist_unnamed_child_runs` is on, and then an identical call returns the recorded run. + Tracked child runs are experimental, so their behavior and interface may change in future versions. + abort_with_parent: Whether the child run is gracefully aborted when this Actor run is gracefully aborted. + `True` or `False` is recorded with the run and replaces the value of an earlier call. `None` keeps the + recorded value, which is `False` for a new run. Without a `run_name` it needs + `Configuration.persist_unnamed_child_runs`. Once this Actor run is being gracefully aborted, a call that + would start a new run with it raises a `RuntimeError`. A hard abort, a timeout or a crash of this Actor + run leaves the child running. + resurrect_with_parent: Whether this call resurrects the child run after it was aborted with this Actor run + through `abort_with_parent`. The call resurrects the run in a process of this Actor run that started + 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`. Returns: Info about the started Actor run. """ - if abort_with_parent and run_name is None: - raise ValueError('`abort_with_parent` requires `run_name`, since only named child runs are tracked.') + is_tracked = run_name is not None or self.configuration.persist_unnamed_child_runs + if abort_with_parent and not is_tracked: + raise ValueError( + '`abort_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since other ' + 'child runs are not tracked.' + ) + if resurrect_with_parent and not is_tracked: + raise ValueError( + '`resurrect_with_parent` requires `run_name` or `Configuration.persist_unnamed_child_runs`, since ' + 'other child runs are not tracked.' + ) - if run_name is not None: + if is_tracked: _warn_child_runs_experimental() if max_items is not None: @@ -1669,7 +1778,7 @@ async def call_task( task_client = client.task(task_id) - if run_name is None: + if not is_tracked: run = await task_client.call( task_input=task_input, build=build, @@ -1682,7 +1791,7 @@ async def call_task( wait_duration=wait, ) else: - started_run, _ = await self._find_or_start_child_run( + key, started_run, _ = await self._find_or_start_child_run( run_name, task_id=task_id, run_input=task_input, @@ -1698,16 +1807,20 @@ async def call_task( run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), ), - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - timeout=timeout, + options=checksum_run_options( + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + timeout=timeout, + webhooks=to_client_representations(webhooks), + ), abort_with_parent=abort_with_parent, + resurrect_with_parent=resurrect_with_parent, ) run = await self._wait_for_child_run( - run_name, client.run(started_run.id), started_run, wait=wait, logger=None, from_start=False + key, client.run(started_run.id), started_run, wait=wait, logger=None, from_start=False ) if run is None: diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index 4b3bc52d..cf254558 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -3,36 +3,49 @@ import asyncio import hashlib import json -from datetime import datetime +from dataclasses import dataclass +from datetime import timedelta from logging import getLogger -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal, NamedTuple from weakref import WeakValueDictionary -from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError +from pydantic import BaseModel, ConfigDict, Field, ValidationError from pydantic.alias_generators import to_camel from apify_client.errors import NotFoundError +from apify_client.http_clients import StreamedRequestBody + +from apify._utils import docs_group if TYPE_CHECKING: from collections.abc import Awaitable, Callable + from decimal import Decimal from apify_client import ApifyClientAsync - from apify_client._models import Run + from apify_client._literals import ActorPermissionLevel + from apify_client._models import Run, WebhookRepresentation from apify_client._resource_clients import RunClientAsync from apify.storages import KeyValueStore logger = getLogger(__name__) -CHILD_RUNS_KEY = '__ACTOR_CHILD_RUNS' +CHILD_RUNS_KEY = 'APIFY_ACTOR_CHILD_RUNS' """Key in the default key-value store under which the child run registry is persisted.""" -_SETTLING_STATUSES = frozenset({'ABORTING', 'TIMING-OUT'}) -"""Statuses that end as `ABORTED` / `TIMED-OUT` shortly, and are resurrectable once they do.""" +_ABORTED_STATUSES = frozenset({'ABORTING', 'ABORTED'}) -_RESURRECTABLE_STATUSES = frozenset({'ABORTED', 'TIMED-OUT'}) +TERMINAL_RUN_STATUSES = frozenset({'SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED-OUT'}) +"""Statuses of a run that is finished. A run in any other status is active.""" -_ABORTED_STATUSES = frozenset({'ABORTING', 'ABORTED'}) +_ABORT_WITH_PARENT_TIMEOUT = timedelta(seconds=10) +"""How long the abort of the child runs with the parent is waited for. + +The platform sends SIGTERM to the parent 15 seconds after the `ABORTING` event, so this leaves time to exit. +""" + +_ABORT_RECORD_TIMEOUT = timedelta(seconds=2) +"""How long the write of what the abort requests returned is waited for, after the abort itself.""" _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.""" @@ -40,49 +53,237 @@ _NOT_FOUND_RETRY_INTERVAL_SECS = 0.25 -class ChildRunSnapshot(BaseModel): - """A child run as last observed by this Actor run.""" +_UNNAMED_KEY_LENGTH = 16 +"""Number of leading hex characters of the checksum that key a run started without a `run_name`.""" + + +class ChildRunKey(NamedTuple): + """Where a child run is recorded in the child run registry.""" + + kind: Literal['named', 'unnamed'] + """The map of the registry that holds the run.""" + + key: str + """Key of the run in that map.""" + + @classmethod + def from_request(cls, run_name: str | None, checksum: str) -> ChildRunKey: + """Return the key of a start: its `run_name`, or the start of its checksum when it has no name.""" + if run_name is not None: + return cls('named', run_name) + return cls('unnamed', checksum[:_UNNAMED_KEY_LENGTH]) - model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel) + +@docs_group('Actor') +class ChildRunRecord(BaseModel): + """A child run as recorded in the child run registry of this Actor run.""" + + model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel, frozen=True) run_id: str """ID of the run.""" + run_name: str | None + """The `run_name` the run was started with, or `None` for a run started without one.""" + status: str - """Last status of the run observed by this Actor run, or `LOST` once the platform no longer returned it.""" + """Last status of the run observed by this Actor run. It can be out of date.""" - started_at: datetime - """When the run started.""" + checksum: str + """SHA-256 of the request the run was started with.""" + abort_with_parent: bool = False + """Whether the run is aborted when this Actor run is gracefully aborted.""" -class ChildRunRecord(ChildRunSnapshot): - """The current run tracked under a name in the child run registry, with the runs it replaced.""" + resurrect_with_parent: bool = False + """Whether a run aborted with this Actor run is resurrected after this Actor run is resurrected.""" - checksum: str - """Hash of the Actor or task and the input the current run was started with.""" + aborted_with_parent: bool = False + """Whether the run was aborted with this Actor run and not resurrected since.""" - history: list[ChildRunSnapshot] = Field(default_factory=list) - """Earlier runs under this name that failed or went missing and were replaced by a new run, oldest first.""" - abort_with_parent: bool = False - """Whether the current run is aborted when this Actor run is gracefully aborted.""" +@docs_group('Actor') +class ChildRun(NamedTuple): + """A child run of this Actor run, as listed in `Actor.child_runs`.""" + + record: ChildRunRecord + """Read-only copy of the record stored in the child run registry.""" + + client: RunClientAsync + """Client for the run.""" -def checksum_request(*, actor_id: str | None, task_id: str | None, run_input: Any) -> str: - """Hash the Actor or task and the input of a named start, in the same JSON shape as the JS SDK.""" +@docs_group('Actor') +@dataclass(frozen=True) +class ChildRuns: + """The child runs of this Actor run, as recorded in the child run registry.""" + + named: dict[str, ChildRun] + """Runs started with a `run_name`, by that name.""" + + unnamed: dict[str, ChildRun] + """Runs started without a `run_name`, by the key derived from their request.""" + + +class _StoredChildRuns(BaseModel): + """The child run registry as stored in the default key-value store.""" + + named: dict[str, ChildRunRecord] = Field(default_factory=dict) + unnamed: dict[str, ChildRunRecord] = Field(default_factory=dict) + + +def _canonical_number(value: float) -> str: + """Serialize a finite float the way `Number.prototype.toString` of ECMAScript does, as RFC 8785 requires.""" + if value == 0: + return '0' + + sign = '-' if value < 0 else '' + mantissa, _, exponent = repr(abs(value)).partition('e') + integer_part, _, fraction_part = mantissa.partition('.') + + # The value equals `0. * 10 ** point`. + all_digits = integer_part + fraction_part + significant_digits = all_digits.lstrip('0') + point = len(integer_part) + int(exponent or 0) - (len(all_digits) - len(significant_digits)) + digits = significant_digits.rstrip('0') + digit_count = len(digits) + + if digit_count <= point <= 21: # noqa: PLR2004 + return f'{sign}{digits}{"0" * (point - digit_count)}' + if 0 < point <= 21: # noqa: PLR2004 + return f'{sign}{digits[:point]}.{digits[point:]}' + if -6 < point <= 0: # noqa: PLR2004 + return f'{sign}0.{"0" * -point}{digits}' + + exponent_sign = '+' if point > 0 else '-' + fraction = f'.{digits[1:]}' if digit_count > 1 else '' + return f'{sign}{digits[0]}{fraction}e{exponent_sign}{abs(point - 1)}' + + +def _canonical_json(value: Any) -> str: + """Serialize a JSON value as canonical JSON (RFC 8785, JCS). + + An integer too large for an IEEE 754 double is written with all its digits, since that is what the client sends. + """ + if value is None: + return 'null' + if value is True: + return 'true' + if value is False: + return 'false' + if isinstance(value, str): + return json.dumps(value, ensure_ascii=False) + if isinstance(value, int): + return str(value) + if isinstance(value, float): + return _canonical_number(value) + if isinstance(value, (list, tuple)): + items = ','.join(_canonical_json(item) for item in value) + return f'[{items}]' + if isinstance(value, dict): + # RFC 8785 sorts the keys by their UTF-16 code units. + sorted_keys = sorted(value, key=lambda key: key.encode('utf-16-be', 'surrogatepass')) + members = [f'{json.dumps(key, ensure_ascii=False)}:{_canonical_json(value[key])}' for key in sorted_keys] + return f'{{{",".join(members)}}}' + raise TypeError(f'Cannot serialize a {type(value).__name__} value as canonical JSON.') + + +def _to_json_input(run_input: Any, content_type: str | None) -> Any: + """Convert the input of a run to the JSON document the client sends to the API. + + Raises: + TypeError: If the client would not send the input as JSON. + """ + if content_type and 'application/json' not in content_type: + raise TypeError( + f'A tracked child run needs a JSON input, but the content type is {content_type!r}. Start the run without ' + 'a `run_name` and with `persist_unnamed_child_runs` off, or through the Apify API client.' + ) + if isinstance(run_input, (str, bytes, bytearray)) or StreamedRequestBody.is_streamable(run_input): + raise TypeError( + f'A tracked child run needs a JSON input, but the input is a {type(run_input).__name__}. Start the run ' + 'without a `run_name` and with `persist_unnamed_child_runs` off, or through the Apify API client.' + ) + serialized = json.dumps(run_input, ensure_ascii=False, allow_nan=False, default=str) + return json.loads(serialized) + + +def checksum_run_options( + *, + build: str | None = None, + max_items: int | None = None, + max_total_charge_usd: Decimal | None = None, + restart_on_error: bool | None = None, + memory_mbytes: int | None = None, + timeout: timedelta | Literal['inherit'] | None = None, + force_permission_level: ActorPermissionLevel | None = None, + webhooks: list[WebhookRepresentation] | None = None, +) -> dict[str, Any]: + """Return the run options that are set, under the names and with the values of the Apify API. + + Args: + build: The Actor build to run. + max_items: Limit of the charged results of a pay-per-result run. + max_total_charge_usd: Limit of the total charged amount of the run. + restart_on_error: Whether the run restarts when its process fails. + memory_mbytes: Memory limit of the run, in megabytes. + timeout: Timeout of the run. `inherit` is kept as the string, since the remaining time of this Actor run + differs in each of its processes. + force_permission_level: Permission level of the run. + webhooks: Ad-hoc webhooks of the run. + """ + timeout_option = int(timeout.total_seconds()) if isinstance(timeout, timedelta) else timeout + + webhook_dicts = [webhook.model_dump(mode='json', by_alias=True, exclude_none=True) for webhook in webhooks or []] + options = { + 'build': build, + 'forcePermissionLevel': force_permission_level, + 'maxItems': max_items, + 'maxTotalChargeUsd': float(max_total_charge_usd) if max_total_charge_usd is not None else None, + 'memory': memory_mbytes, + 'restartOnError': restart_on_error, + 'timeout': timeout_option, + 'webhooks': webhook_dicts or None, + } + return {name: value for name, value in options.items() if value is not None} + + +def checksum_request( + *, + actor_id: str | None = None, + task_id: str | None = None, + run_input: Any = None, + content_type: str | None = None, + options: dict[str, Any] | None = None, +) -> str: + """Hash the Actor or task, the input, and the run options of a start, in the same JSON shape as the JS SDK. + + Args: + actor_id: The Actor to start. + task_id: The task to start, in place of `actor_id`. + run_input: Input of the run. + content_type: Content type of the input. + options: Run options from `checksum_run_options`. + + Raises: + TypeError: If the client would not send the input as JSON. + """ request: dict[str, Any] = ( {'type': 'actor', 'id': actor_id} if actor_id is not None else {'type': 'task', 'id': task_id} ) - if run_input is not None: - request['input'] = run_input - serialized = json.dumps(request, sort_keys=True, separators=(',', ':'), ensure_ascii=False, default=str) - return hashlib.sha256(serialized.encode()).hexdigest() + json_input = _to_json_input(run_input, content_type) + if json_input is not None: + request['input'] = json_input + if options: + request['options'] = options + serialized = _canonical_json(request) + return hashlib.sha256(serialized.encode('utf-8', 'surrogatepass')).hexdigest() async def _get_recorded_run(run_client: RunClientAsync) -> Run | None: """Fetch a recorded run, retrying a 404 for a few seconds. - A run started moments ago, e.g. by a concurrent call under the same name, may not be on every API replica yet, + A run started moments ago, e.g. by a concurrent call under the same key, may not be on every API replica yet, and treating it as gone would start a duplicate. """ loop = asyncio.get_running_loop() @@ -94,228 +295,384 @@ async def _get_recorded_run(run_client: RunClientAsync) -> Run | None: await asyncio.sleep(_NOT_FOUND_RETRY_INTERVAL_SECS) -_records_adapter = TypeAdapter(dict[str, ChildRunRecord]) - - class ChildRunRegistry: - """Persisted name -> run map that lets named child runs survive a migration or resurrection of the parent. + """Persisted key -> run map that lets child runs survive a migration, reboot, or resurrection of the parent. Every change is written to the key-value store right away. A hard kill of the parent between the platform starting the child and that write can still orphan the child, since nothing but the platform knows about it. """ - def __init__(self, open_key_value_store: Callable[[], Awaitable[KeyValueStore]]) -> None: + def __init__( + self, + open_key_value_store: Callable[[], Awaitable[KeyValueStore]], + *, + is_parent_aborting: Callable[[], Awaitable[bool]] | None = None, + ) -> None: + """Initialize a new instance. + + Args: + open_key_value_store: Opens the default key-value store of this Actor run. + is_parent_aborting: Asks the platform whether this Actor run is being gracefully aborted. A process that + starts during the abort gets no `ABORTING` event, so this is how it learns about the abort. + """ self._open_key_value_store = open_key_value_store - self._records: dict[str, ChildRunRecord] | None = None + self._is_parent_aborting = is_parent_aborting + self._parent_status_checked = False + """Whether `is_parent_aborting` was already asked in this process.""" + self._stored: _StoredChildRuns | None = None + self._loaded = asyncio.Event() + """Set once the Actor has read the records from the key-value store, or has failed to.""" self._lock = asyncio.Lock() """Guards loading the records and writing them back to the key-value store.""" - self._name_locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary() - """Serializes `find_or_start` per name. A lock is dropped once no call under its name holds it.""" - self._clients: dict[str, ApifyClientAsync] = {} - """Client the run under each name was last started or looked up with. Lost on a migration.""" + self._key_locks: WeakValueDictionary[ChildRunKey, asyncio.Lock] = WeakValueDictionary() + """Serializes `find_or_start` per key. A lock is dropped once no call under its key holds it.""" + self._clients: dict[ChildRunKey, 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 + """The abort of the child runs with the parent, once the parent is being gracefully aborted.""" async def find_or_start( self, - name: str, + key: ChildRunKey, *, - actor_id: str | None = None, - task_id: str | None = None, - run_input: Any, + checksum: str, client: ApifyClientAsync, start_run: Callable[[], Awaitable[Run]], - resurrect_run: Callable[[str], Awaitable[Run]], - abort_with_parent: bool = False, + abort_with_parent: bool | None = None, + resurrect_with_parent: bool | None = None, ) -> tuple[Run, bool]: - """Return the run recorded under `name`, or start one when there is none to reuse. + """Return the run recorded under `key`, or start one when there is none. - A recorded run that is `READY` or `RUNNING` is reattached and one that `SUCCEEDED` is returned as is. - An `ABORTED` or `TIMED-OUT` run is resurrected, since Actors are expected to resume from their state. - A `FAILED` run, or one the API no longer knows, is replaced by a new run under the same name, for any Actor, - task or input. + A recorded run is returned in whatever status it is in, except for a run that was aborted with the parent and + is marked `resurrect_with_parent`, which is resurrected first. Only a recorded run that the API no longer knows + is replaced by a new run under the same key. Args: - name: Name of the child run, unique within the parent run. - actor_id: The Actor to start. - task_id: The task to start, in place of `actor_id`. - run_input: Input of the run. The recorded run is reused only if it was started with the same Actor or task - and input. + key: Key of the child run, unique within the parent run. + checksum: Hash of the request from `checksum_request`. The recorded run is returned only if it was + 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. - resurrect_run: Resurrects the recorded run, given its ID. - abort_with_parent: Whether to abort the run when this Actor run is gracefully aborted. It replaces the value - recorded under `name`. + abort_with_parent: Whether to abort the run when this Actor run is gracefully aborted. `True` or `False` + 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`. Returns: The run, and whether it was newly started. Raises: - ValueError: If the recorded run would be reused, but was started for a different Actor, task or input. - RuntimeError: If `abort_with_parent` is set and this Actor run is being gracefully aborted. No run is - started, resurrected or reattached. + ValueError: If the run recorded under `key` was started with a different request. + RuntimeError: If a new run marked `abort_with_parent` would start while this Actor run is being + gracefully aborted. No run is started. """ - checksum = checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input) + async with self._key_locks.setdefault(key, asyncio.Lock()): + record = self._records(key.kind).get(key.key) + + if abort_with_parent is None: + abort_with_parent = record.abort_with_parent if record is not None else False + if resurrect_with_parent is None: + resurrect_with_parent = record.resurrect_with_parent if record is not None else False + + if record is not None: + if record.checksum != checksum: + if key.kind == 'unnamed': + raise ValueError( + f'The key "{key.key}" of this child run is taken by a run of a different Actor, task, ' + 'input or run options. Pass a `run_name` to start it.' + ) + raise ValueError( + f'The run name "{key.key}" was already used for a different Actor, task, input or run options. ' + 'Use a unique `run_name` for each child run.' + ) + + run_client = client.run(record.run_id) + run = await _get_recorded_run(run_client) + # The abort of the child runs flags the records without the lock of the key, also during the request. + record = self._records(key.kind)[key.key] + aborted_with_parent = record.aborted_with_parent + + if run is not None and aborted_with_parent and resurrect_with_parent: + run, aborted_with_parent = await self._resurrect_with_parent(key, run_client, run) + elif run is not None and run.status not in _ABORTED_STATUSES and not self._parent_aborting: + # The run finished first or someone resurrected it, so the flag no longer applies. + aborted_with_parent = False + + if run is not None: + log_extra = {'run_id': run.id, 'status': run.status} + logger.info('Reattaching to child run "%s"', key.key, extra=log_extra) + # An abort of the child runs that began during the awaits above keeps its flag. + record = self._records(key.kind)[key.key] + if self._parent_aborting: + aborted_with_parent = aborted_with_parent or record.aborted_with_parent + updated_record = record.model_copy( + update={ + 'status': run.status, + 'abort_with_parent': abort_with_parent, + 'resurrect_with_parent': resurrect_with_parent, + 'aborted_with_parent': aborted_with_parent, + } + ) + if updated_record != record: + await self._save(key, updated_record) + self._clients[key] = client + return run, False + + logger.warning( + 'Child run "%s" no longer exists, starting a new run in its place', + key.key, + extra={'run_id': record.run_id}, + ) - async with self._name_locks.setdefault(name, asyncio.Lock()): if abort_with_parent and self._parent_aborting: raise RuntimeError( - f'Child run "{name}" with `abort_with_parent` was not started, since this Actor run is being ' + f'Child run "{key.key}" with `abort_with_parent` was not started, since this Actor run is being ' 'aborted.' ) - records = await self._load() - record = records.get(name) - - if record is None: - run = await self._start( - name, checksum=checksum, start_run=start_run, history=[], abort_with_parent=abort_with_parent - ) - self._clients[name] = client - return run, True - - run_client = client.run(record.run_id) - run = await _get_recorded_run(run_client) - - if run is not None and run.status in _SETTLING_STATUSES: - run = await run_client.wait_for_finish() - - if run is None or run.status == 'FAILED': - replaced = ChildRunSnapshot( - run_id=record.run_id, - status=run.status if run is not None else 'LOST', - started_at=record.started_at, - ) - run = await self._start( - name, - checksum=checksum, - start_run=start_run, - history=[*record.history, replaced], - abort_with_parent=abort_with_parent, - ) - self._clients[name] = client - return run, True + 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(), + ) + await self._save(key, new_record) + self._clients[key] = client + return run, True - if record.checksum != checksum: - raise ValueError( - f'The run name "{name}" was already used for a different Actor, task or input. ' - 'Use a unique `run_name` for each child run.' - ) + async def _resurrect_with_parent( + self, key: ChildRunKey, run_client: RunClientAsync, run: Run + ) -> tuple[Run | None, bool]: + """Resurrect a run that was aborted with the parent, unless the parent is being aborted now. - if record.abort_with_parent != abort_with_parent: - await self._save(name, record.model_copy(update={'abort_with_parent': abort_with_parent})) + Returns: + 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._parent_status_checked = True + + # The process that aborts the children must not resurrect them. + if self._parent_aborting: + return run, True + + if run.status == 'ABORTING': + finished_run = await run_client.wait_for_finish() + if finished_run is None: + return None, False + run = finished_run + + # The run finished or was resurrected in the meantime, so the abort with the parent no longer applies to it. + if run.status != 'ABORTED': + return run, False - if run.status in _RESURRECTABLE_STATUSES: - logger.info('Resurrecting child run "%s"', name, extra={'run_id': run.id, 'status': run.status}) - run = await resurrect_run(run.id) - else: - logger.info('Reattaching to child run "%s"', name, extra={'run_id': run.id, 'status': run.status}) + # The parent may have got `ABORTING` while this call waited for the run to be aborted. + if self._parent_aborting: + return run, True - await self.update(name, run) - self._clients[name] = client - return run, False + logger.info('Resurrecting child run "%s" with the parent', key.key, extra={'run_id': run.id}) + try: + resurrected_run = await run_client.resurrect() + except NotFoundError: + return None, False + return resurrected_run, False - def run_clients(self, default_client: ApifyClientAsync) -> dict[str, RunClientAsync]: - """Return a client for the current run under each recorded name. + def child_runs(self, default_client: ApifyClientAsync) -> ChildRuns: + """Return the record and a client for the run under each recorded key. - Each client comes from the client its name was last started or looked up with in this process, so a run started + Each client comes from the client its key was last started or looked up with in this process, so a run started with a custom token uses that token. Args: - default_client: Client used for a name not started or looked up in this process, e.g. one recorded before a - migration. + default_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. """ - return { - name: self._clients.get(name, default_client).run(record.run_id) - for name, record in (self._records or {}).items() - } + child_runs: dict[str, dict[str, ChildRun]] = {'named': {}, 'unnamed': {}} + for kind in ('named', 'unnamed'): + for key, record in self._records(kind).items(): + client = self._clients.get(ChildRunKey(kind, key), default_client) + child_runs[kind][key] = ChildRun(record=record, client=client.run(record.run_id)) + return ChildRuns(named=child_runs['named'], unnamed=child_runs['unnamed']) - async def update(self, name: str, run: Run) -> None: - """Record the latest observed status of the run recorded under `name`. + async def update(self, key: ChildRunKey, run: Run) -> None: + """Record the latest observed status of the run recorded under `key`. Args: - name: Name of the child run. - run: The run as just returned by the API. Nothing is recorded unless it is the current run under `name`. + key: Key of the child run. + run: The run as just returned by the API. Nothing is recorded unless it is the run under `key`. """ - record = (await self._load()).get(name) + record = self._records(key.kind).get(key.key) if record is None or record.run_id != run.id or record.status == run.status: return - await self._save(name, record.model_copy(update={'status': run.status})) + await self._save(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. 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. + the start records it. The aborts are waited for at most `_ABORT_WITH_PARENT_TIMEOUT`. Args: - client: Client used for a name not started or looked up in this process, e.g. after a migration. + 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 - records = await self._load() - # Names with a start in flight are not recorded yet, so their locks are awaited too. - await asyncio.gather(*(self._abort(name, client) for name in {*records, *self._name_locks})) + 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) + + 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: + await asyncio.shield(self._abort_task) + + async def _abort_runs_with_parent(self, client: ApifyClientAsync) -> None: + updated_keys = set[ChildRunKey]() + try: + async with asyncio.timeout(_ABORT_WITH_PARENT_TIMEOUT.total_seconds()): + # The event can arrive 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. + if self._stored is None: + return + recorded_keys = {ChildRunKey(kind, key) for kind in ('named', 'unnamed') for key in self._records(kind)} + await self._flag_runs_to_abort(recorded_keys) + # Keys with a start in flight are not recorded yet, so their locks are awaited too. + aborts = [self._abort(key, client, updated_keys) for key in {*recorded_keys, *self._key_locks}] + await asyncio.gather(*aborts) + except TimeoutError: + logger.warning( + 'Aborting the child runs with the parent did not finish in %.3g seconds', + _ABORT_WITH_PARENT_TIMEOUT.total_seconds(), + ) + finally: + if updated_keys: + await self._write_abort_results() + + def _is_abort_in_progress(self) -> bool: + """Whether the abort of the child runs with the parent has started and still has runs to abort.""" + return self._abort_task is not None and not self._abort_task.done() + + async def _flag_runs_to_abort(self, keys: set[ChildRunKey]) -> None: + """Set `aborted_with_parent` for the recorded runs that the abort is about to stop, in one write. - async def _abort(self, name: str, default_client: ApifyClientAsync) -> None: - async with self._name_locks.setdefault(name, asyncio.Lock()): - record = (await self._load()).get(name) + The write goes out before the abort requests, so the flags survive a parent that is killed during the abort. + A run recorded as finished was not stopped by this abort, unless its abort request shows otherwise. A failed + or slow write is logged and does not stop the abort. + """ + flagged = False + for key in keys: + record = self._records(key.kind)[key.key] + if ( + record.abort_with_parent + and not record.aborted_with_parent + and record.status not in TERMINAL_RUN_STATUSES + ): + self._records(key.kind)[key.key] = record.model_copy(update={'aborted_with_parent': True}) + flagged = True + if not flagged: + return + # The abort requests go out also when the key-value store is slow or fails. + try: + async with asyncio.timeout(_ABORT_RECORD_TIMEOUT.total_seconds()): + await self._write() + except TimeoutError: + logger.warning( + 'Recording the child runs to abort with the parent did not finish in %.3g seconds', + _ABORT_RECORD_TIMEOUT.total_seconds(), + ) + except Exception: + logger.exception('Failed to record the child runs to abort with the parent') + + async def _write_abort_results(self) -> None: + """Write what the abort requests returned, with a time limit apart from the one of the abort itself.""" + try: + async with asyncio.timeout(_ABORT_RECORD_TIMEOUT.total_seconds()): + await self._write() + except TimeoutError: + logger.warning( + 'Recording the child runs aborted with the parent did not finish in %.3g seconds', + _ABORT_RECORD_TIMEOUT.total_seconds(), + ) + except Exception: + logger.exception('Failed to record the child runs aborted with the parent') + + async def _abort(self, key: ChildRunKey, default_client: ApifyClientAsync, updated_keys: set[ChildRunKey]) -> None: + async with self._key_locks.setdefault(key, asyncio.Lock()): + record = self._records(key.kind).get(key.key) if record is None or not record.abort_with_parent: return - run_client = self._clients.get(name, default_client).run(record.run_id) + 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', name, extra={'run_id': record.run_id}) + logger.debug('Child run "%s" no longer exists', key.key, extra={'run_id': record.run_id}) + self._clear_aborted_with_parent(key, updated_keys) except Exception: - logger.exception('Failed to abort child run "%s"', name, extra={'run_id': record.run_id}) + logger.exception('Failed to abort child run "%s"', key.key, extra={'run_id': record.run_id}) + self._clear_aborted_with_parent(key, updated_keys) else: + # A run that the request found `ABORTED` was stopped by this abort only if it was active before it. + was_active = record.aborted_with_parent or record.status not in TERMINAL_RUN_STATUSES + aborted = run.status == 'ABORTING' or (run.status == 'ABORTED' and was_active) + updated_record = record.model_copy(update={'status': run.status, 'aborted_with_parent': aborted}) + if updated_record != record: + self._records(key.kind)[key.key] = updated_record + updated_keys.add(key) if run.status in _ABORTED_STATUSES: - logger.info('Aborted child run "%s" with the parent', name, extra={'run_id': record.run_id}) + logger.info('Aborted child run "%s" with the parent', key.key, extra={'run_id': record.run_id}) - async def _start( - self, - name: str, - *, - checksum: str, - start_run: Callable[[], Awaitable[Run]], - history: list[ChildRunSnapshot], - abort_with_parent: bool, - ) -> Run: - run = await start_run() - record = ChildRunRecord( - run_id=run.id, - status=run.status, - started_at=run.started_at, - checksum=checksum, - history=history, - abort_with_parent=abort_with_parent, - ) - await self._save(name, record) - return run + def _clear_aborted_with_parent(self, key: ChildRunKey, updated_keys: set[ChildRunKey]) -> None: + """Drop the flag of a run whose abort request failed, since nothing shows that this abort stopped the run.""" + record = self._records(key.kind)[key.key] + if record.aborted_with_parent: + self._records(key.kind)[key.key] = record.model_copy(update={'aborted_with_parent': False}) + updated_keys.add(key) - async def load(self) -> dict[str, ChildRunRecord]: + async def load(self) -> None: """Read the records from the default key-value store, replacing any read before.""" async with self._lock: - key_value_store = await self._open_key_value_store() - stored = await key_value_store.get_value(CHILD_RUNS_KEY) try: - self._records = _records_adapter.validate_python(stored or {}) - except ValidationError as exc: - raise ValueError( - f'The child run registry under the "{CHILD_RUNS_KEY}" key in the default key-value store ' - 'is malformed.' - ) from exc - return self._records - - async def _load(self) -> dict[str, ChildRunRecord]: - return self._records if self._records is not None else await self.load() - - async def _save(self, name: str, record: ChildRunRecord) -> None: - records = await self._load() + key_value_store = await self._open_key_value_store() + stored = await key_value_store.get_value(CHILD_RUNS_KEY) + try: + self._stored = _StoredChildRuns.model_validate({} if stored is None else stored) + except ValidationError as exc: + raise ValueError( + f'The child run registry under the "{CHILD_RUNS_KEY}" key in the default key-value store ' + 'is malformed.' + ) from exc + finally: + self._loaded.set() + + def stop_waiting_for_load(self) -> None: + """Release an abort of the child runs that waits for the registry, when the Actor fails before it loads it.""" + self._loaded.set() + + def _records(self, kind: Literal['named', 'unnamed']) -> dict[str, ChildRunRecord]: + if self._stored is None: + raise RuntimeError('The child run registry is not loaded.') + return self._stored.named if kind == 'named' else self._stored.unnamed + + async def _save(self, key: ChildRunKey, record: ChildRunRecord) -> None: + self._records(key.kind)[key.key] = record + await self._write() + + async def _write(self) -> None: + """Write all the records to the default key-value store.""" key_value_store = await self._open_key_value_store() async with self._lock: - records[name] = record - await key_value_store.set_value( - CHILD_RUNS_KEY, _records_adapter.dump_python(records, by_alias=True, mode='json') - ) + stored = self._stored.model_dump(mode='json', by_alias=True) if self._stored is not None else {} + await key_value_store.set_value(CHILD_RUNS_KEY, stored) diff --git a/src/apify/_configuration.py b/src/apify/_configuration.py index c6c15841..0c7a3a86 100644 --- a/src/apify/_configuration.py +++ b/src/apify/_configuration.py @@ -360,6 +360,18 @@ class Configuration(CrawleeConfiguration): ), ] = timedelta(minutes=5) + persist_unnamed_child_runs: Annotated[ + bool, + Field( + validation_alias='apify_persist_unnamed_child_runs', + description=( + 'Whether the runs that `Actor.start`, `Actor.call`, `Actor.start_task`, and `Actor.call_task` start ' + 'without a `run_name` are recorded in the default key-value store and reused by an identical call. ' + 'Such a call then needs a JSON input, and the store suits at most a few thousand recorded runs' + ), + ), + ] = False + proxy_hostname: Annotated[ str, Field( diff --git a/src/apify/_consts.py b/src/apify/_consts.py index e7c39dea..43172fdd 100644 --- a/src/apify/_consts.py +++ b/src/apify/_consts.py @@ -81,6 +81,7 @@ class ApifyEnvVars(StrEnum): METAMORPH_AFTER_SLEEP_MILLIS = 'APIFY_METAMORPH_AFTER_SLEEP_MILLIS' PERSIST_STATE_INTERVAL_MILLIS = 'APIFY_PERSIST_STATE_INTERVAL_MILLIS' PERSIST_STORAGE = 'APIFY_PERSIST_STORAGE' + PERSIST_UNNAMED_CHILD_RUNS = 'APIFY_PERSIST_UNNAMED_CHILD_RUNS' PROXY_HOSTNAME = 'APIFY_PROXY_HOSTNAME' PROXY_PASSWORD = 'APIFY_PROXY_PASSWORD' PROXY_PORT = 'APIFY_PROXY_PORT' diff --git a/tests/e2e/test_actor_child_runs.py b/tests/e2e/test_actor_child_runs.py index 05b1352a..f86317ff 100644 --- a/tests/e2e/test_actor_child_runs.py +++ b/tests/e2e/test_actor_child_runs.py @@ -36,8 +36,8 @@ async def main() -> None: return child_runs = Actor.child_runs - assert child_runs.keys() == {'child'}, f'child_runs={child_runs}' - assert child_runs['child'].resource_id == child_run_id, f'child_runs={child_runs}' + assert child_runs.named.keys() == {'child'}, f'child_runs={child_runs}' + assert child_runs.named['child'].client.resource_id == child_run_id, f'child_runs={child_runs}' run = await Actor.call(actor_id=actor_id, run_input={'is_child': True}, run_name='child') assert run is not None, 'run is None' @@ -52,11 +52,11 @@ async def main() -> None: assert (await actor.runs().list()).total == 2 -async def test_named_aborted_child_run_is_resurrected_after_reboot( +async def test_named_aborted_child_run_is_returned_aborted_after_reboot( make_actor: MakeActorFunction, run_actor: RunActorFunction, ) -> None: - """A named child run aborted before a reboot is resurrected by a named start after it.""" + """A named child run aborted before a reboot is returned `ABORTED` by a named start after it.""" async def main() -> None: async with Actor: @@ -80,17 +80,14 @@ async def main() -> None: return run = await Actor.start(actor_id=actor_id, run_input={'is_child': True}, run_name='child') - try: - assert run.id == child_run_id, f'run.id={run.id}, child_run_id={child_run_id}' - assert run.status in {'READY', 'RUNNING'}, f'run.status={run.status}' - finally: - await Actor.apify_client.run(run.id).abort() + assert run.id == child_run_id, f'run.id={run.id}, child_run_id={child_run_id}' + assert run.status == 'ABORTED', f'run.status={run.status}' - actor = await make_actor(label='child-run-resurrect', main_func=main) + actor = await make_actor(label='child-run-aborted', main_func=main) run_result = await run_actor(actor) assert run_result.status == 'SUCCEEDED' - # The parent run and the one child run it resurrected. + # The parent run and the one child run it started. assert (await actor.runs().list()).total == 2 @@ -123,7 +120,7 @@ async def main() -> None: else: raise AssertionError('The parent run did not record the child run in time.') - child_run_id = record['value']['child']['runId'] + child_run_id = record['value']['named']['child']['runId'] parent_run_client = apify_client_async.run(parent_run.id) await parent_run_client.abort(gracefully=True) await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=120)) @@ -131,3 +128,68 @@ async def main() -> None: child_run = await apify_client_async.run(child_run_id).wait_for_finish(wait_duration=timedelta(seconds=120)) assert child_run is not None assert child_run.status == 'ABORTED' + + +async def test_named_child_run_is_resurrected_with_parent( + make_actor: MakeActorFunction, + apify_client_async: ApifyClientAsync, +) -> None: + """A child run aborted with the parent is resurrected by the same call after the parent is resurrected.""" + + async def main() -> None: + async with Actor: + actor_input = (await Actor.get_input()) or {} + if actor_input.get('is_child') is True: + await asyncio.sleep(300) + return + + actor_id = Actor.configuration.actor_id or '' + is_resurrected = 'child' in Actor.child_runs.named + run = await Actor.start( + actor_id=actor_id, + run_input={'is_child': True}, + run_name='child', + abort_with_parent=True, + resurrect_with_parent=True, + ) + + if not is_resurrected: + await asyncio.sleep(300) + return + + assert run.status in {'READY', 'RUNNING'}, f'run.status={run.status}' + await Actor.apify_client.run(run.id).abort() + + actor = await make_actor(label='child-run-resurrect-parent', main_func=main) + parent_run = await actor.start() + parent_kvs = apify_client_async.key_value_store(parent_run.default_key_value_store_id) + + # Wait for the parent to record the child run. + for _ in range(60): + if record := await parent_kvs.get_record(CHILD_RUNS_KEY): + break + await asyncio.sleep(2) + else: + raise AssertionError('The parent run did not record the child run in time.') + + child_run_id = record['value']['named']['child']['runId'] + child_run_client = apify_client_async.run(child_run_id) + parent_run_client = apify_client_async.run(parent_run.id) + await parent_run_client.abort(gracefully=True) + await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=120)) + aborted_child_run = await child_run_client.wait_for_finish(wait_duration=timedelta(seconds=120)) + assert aborted_child_run is not None + assert aborted_child_run.status == 'ABORTED' + + await parent_run_client.resurrect() + resurrected_parent_run = await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=300)) + assert resurrected_parent_run is not None + assert resurrected_parent_run.status == 'SUCCEEDED' + + record = await parent_kvs.get_record(CHILD_RUNS_KEY) + assert record is not None + assert record['value']['named']['child']['runId'] == child_run_id + assert record['value']['named']['child']['abortedWithParent'] is False + child_run = await child_run_client.get() + assert child_run is not None + assert child_run.stats.resurrect_count == 1 diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 48fe1842..8e931091 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1,21 +1,34 @@ from __future__ import annotations import asyncio +import hashlib +import io import warnings from datetime import timedelta +from decimal import Decimal from typing import TYPE_CHECKING, Any from unittest.mock import AsyncMock, MagicMock, Mock import pytest +from pydantic import ValidationError from apify_client._models import Run from apify_client.errors import NotFoundError from crawlee import service_locator from crawlee.events import Event, EventAbortingData -from apify import Actor, Configuration, _child_runs +from apify import Actor, ApifyEnvVars, Configuration, Webhook, _child_runs from apify._actor import _ActorType -from apify._child_runs import CHILD_RUNS_KEY, ChildRunRegistry, checksum_request +from apify._child_runs import ( + CHILD_RUNS_KEY, + ChildRunKey, + ChildRunRecord, + ChildRunRegistry, + ChildRuns, + checksum_request, + checksum_run_options, +) +from apify._webhook import to_client_representations from apify.events import ApifyEventManager if TYPE_CHECKING: @@ -25,7 +38,7 @@ from apify.storages import KeyValueStore -pytestmark = pytest.mark.filterwarnings('ignore:Named child runs:UserWarning') +pytestmark = pytest.mark.filterwarnings('ignore:Tracked child runs:UserWarning') def make_run(run_id: str, status: str) -> Run: @@ -55,23 +68,42 @@ def stored_record( run_id: str, status: str, *, + run_name: str | None = 'scrape-eu', actor_id: str | None = 'some-actor', task_id: str | None = None, run_input: Any = None, - history: list[dict[str, str]] | None = None, + options: dict[str, Any] | None = None, abort_with_parent: bool = False, + resurrect_with_parent: bool = False, + aborted_with_parent: bool = False, ) -> dict[str, Any]: """Build a registry record as it is stored in the default KVS.""" return { 'runId': run_id, + 'runName': run_name, 'status': status, - 'startedAt': STARTED_AT, - 'checksum': checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input), - 'history': history or [], + 'checksum': checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input, options=options), 'abortWithParent': abort_with_parent, + 'resurrectWithParent': resurrect_with_parent, + 'abortedWithParent': aborted_with_parent, } +async def seed_registry(named: dict[str, dict[str, Any]]) -> KeyValueStore: + """Store named records the way an earlier process of this Actor run would have left them, and reload them.""" + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(named)) + await Actor._child_run_registry.load() + return kvs + + +def stored_registry( + named: dict[str, dict[str, Any]] | None = None, unnamed: dict[str, dict[str, Any]] | None = None +) -> dict[str, Any]: + """Build the registry value as it is stored in the default KVS.""" + return {'named': named or {}, 'unnamed': unnamed or {}} + + @pytest.fixture def apify_event_manager() -> ApifyEventManager: """Make the Actor use `ApifyEventManager`, which delivers `ABORTING` on the platform, without a websocket.""" @@ -80,6 +112,12 @@ def apify_event_manager() -> ApifyEventManager: return event_manager +@pytest.fixture +def persist_unnamed_child_runs(monkeypatch: pytest.MonkeyPatch) -> None: + """Turn on `Configuration.persist_unnamed_child_runs` for the Actor of the test.""" + monkeypatch.setenv(ApifyEnvVars.PERSIST_UNNAMED_CHILD_RUNS, '1') + + async def record_child_run( name: str, run_id: str, @@ -87,11 +125,14 @@ async def record_child_run( actor_id: str | None = 'some-actor', task_id: str | None = None, run_input: Any = None, + options: dict[str, Any] | None = None, ) -> None: - """Seed the registry the way an earlier attempt of this Actor run would have left it, and reload it like init.""" + """Seed the registry the way an earlier process of this Actor run would have left it, and reload it like init.""" kvs = await Actor.open_key_value_store() - record = stored_record(run_id, 'RUNNING', actor_id=actor_id, task_id=task_id, run_input=run_input) - await kvs.set_value(CHILD_RUNS_KEY, {name: record}) + record = stored_record( + run_id, 'RUNNING', run_name=name, actor_id=actor_id, task_id=task_id, run_input=run_input, options=options + ) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({name: record})) await Actor._child_run_registry.load() @@ -105,127 +146,280 @@ async def test_named_start_records_run_in_kvs(apify_client_async_patcher: ApifyC stored = await kvs.get_value(CHILD_RUNS_KEY) assert run.id == 'new-run' - assert stored == {'scrape-eu': stored_record('new-run', 'READY')} + assert stored == stored_registry({'scrape-eu': stored_record('new-run', 'READY')}) async def test_unnamed_start_is_not_recorded(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A start without a name leaves the registry untouched.""" + """With persistence off, a start without a name leaves the registry untouched and always starts a new run.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) async with Actor: + await Actor.start('some-actor') await Actor.start('some-actor') kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) assert stored is None + assert len(apify_client_async_patcher.calls['actor']['start']) == 2 + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_is_recorded_with_persistence_on( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence on, a start without a name is recorded under the first 16 characters of its checksum.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + run = await Actor.start('some-actor', {'page': 1}) + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + record = stored_record('new-run', 'READY', run_name=None, run_input={'page': 1}) + assert run.id == 'new-run' + assert stored == stored_registry(unnamed={record['checksum'][:16]: record}) + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_identical_unnamed_starts_share_one_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """With persistence on, an identical start without a name returns the recorded run, and a different one does not.""" + start_run = Mock(side_effect=[make_run('first-run', 'READY'), make_run('second-run', 'READY')]) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('first-run', 'FAILED')) + + async with Actor: + first = await Actor.start('some-actor', {'page': 1}, memory_mbytes=512) + repeated = await Actor.start('some-actor', {'page': 1}, memory_mbytes=512) + other_input = await Actor.start('some-actor', {'page': 2}, memory_mbytes=512) + unnamed = Actor.child_runs.unnamed + + assert first.id == 'first-run' + assert repeated.id == 'first-run' + assert repeated.status == 'FAILED' + assert other_input.id == 'second-run' + assert start_run.call_count == 2 + assert {child_run.record.run_id for child_run in unnamed.values()} == {'first-run', 'second-run'} + assert all(child_run.record.run_name is None for child_run in unnamed.values()) + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_reuses_run_recorded_before_init( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence on, a start without a name returns the run an earlier process recorded for the same request.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'RUNNING')) + record = stored_record('old-run', 'RUNNING', run_name=None, run_input={'page': 1}) + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(unnamed={record['checksum'][:16]: record})) + + async with Actor: + run = await Actor.start('some-actor', {'page': 1}) + + assert run.id == 'old-run' + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_named_and_unnamed_runs_of_one_request_are_separate( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A named start and a start without a name with the same request are recorded as two runs.""" + start_run = Mock(side_effect=[make_run('unnamed-run', 'READY'), make_run('named-run', 'READY')]) + apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run) + + async with Actor: + await Actor.start('some-actor') + key = checksum_request(actor_id='some-actor')[:16] + await Actor.start('some-actor', run_name=key) + child_runs = Actor.child_runs + + assert child_runs.unnamed[key].client.resource_id == 'unnamed-run' + assert child_runs.named[key].client.resource_id == 'named-run' + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_rejects_key_taken_by_another_request( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A start without a name whose key holds a run of another request raises and starts no run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + key = checksum_request(actor_id='some-actor')[:16] + record = stored_record('old-run', 'RUNNING', run_name=None, actor_id='other-actor') + + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(unnamed={key: record})) + await Actor._child_run_registry.load() + with pytest.raises(ValueError, match='is taken by a run of a different Actor'): + await Actor.start('some-actor') + + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') @pytest.mark.parametrize( - 'status', + ('method', 'resource'), [ - pytest.param('READY', id='ready'), - pytest.param('RUNNING', id='running'), - pytest.param('SUCCEEDED', id='succeeded'), + pytest.param('call', 'actor', id='call'), + pytest.param('call_task', 'task', id='call task'), ], ) -async def test_named_start_reuses_recorded_run( - apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +async def test_unnamed_call_is_recorded_with_persistence_on( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str ) -> None: - """A recorded run that is active or succeeded is returned without starting a new one.""" - apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) + """With persistence on, a call without a name starts the run, waits for it, and records its final status.""" + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch(resource, 'call', return_value=make_run('other-run', 'SUCCEEDED')) + 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: - await record_child_run('scrape-eu', 'old-run') - run = await Actor.start('some-actor', run_name='scrape-eu') + run = await getattr(Actor, method)('some-id', **kwargs) + [child_run] = Actor.child_runs.unnamed.values() - assert run.id == 'old-run' - assert run.status == status - assert apify_client_async_patcher.calls['actor']['start'] == [] + assert run.id == 'new-run' + assert run.status == 'SUCCEEDED' + assert child_run.record.status == 'SUCCEEDED' + assert apify_client_async_patcher.calls[resource]['call'] == [] + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_task_is_recorded_with_persistence_on( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence on, a task start without a name is recorded and reused by an identical start.""" + apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('new-run', 'RUNNING')) + + async with Actor: + await Actor.start_task('some-task', {'page': 1}) + repeated = await Actor.start_task('some-task', {'page': 1}) + unnamed = Actor.child_runs.unnamed + + key = checksum_request(task_id='some-task', run_input={'page': 1})[:16] + assert repeated.status == 'RUNNING' + assert unnamed.keys() == {key} + assert len(apify_client_async_patcher.calls['task']['start']) == 1 @pytest.mark.parametrize( - 'status', + ('method', 'resource'), [ - pytest.param('ABORTED', id='aborted'), - pytest.param('TIMED-OUT', id='timed out'), + pytest.param('call', 'actor', id='call'), + pytest.param('call_task', 'task', id='call task'), ], ) -async def test_named_start_resurrects_recorded_run( - apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +async def test_unnamed_call_uses_the_client_call_with_persistence_off( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str ) -> None: - """A recorded run that was aborted or timed out is resurrected, and its options are passed through.""" + """With persistence off, a call without a name goes to the client's `call` and records nothing.""" + apify_client_async_patcher.patch(resource, 'call', return_value=make_run('new-run', 'SUCCEEDED')) + + async with Actor: + run = await getattr(Actor, method)('some-id') + child_runs = Actor.child_runs + + assert run.id == 'new-run' + assert len(apify_client_async_patcher.calls[resource]['call']) == 1 + assert child_runs == ChildRuns(named={}, unnamed={}) + + +async def test_unnamed_start_accepts_any_input_with_persistence_off( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence off, a start without a name passes an input that is not JSON to the client.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) - apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) async with Actor: - await record_child_run('scrape-eu', 'old-run') - run = await Actor.start('some-actor', run_name='scrape-eu', memory_mbytes=2048) + await Actor.start('some-actor', 'plain text', content_type='text/plain') + + [(_, kwargs)] = apify_client_async_patcher.calls['actor']['start'] + assert kwargs['run_input'] == 'plain text' + assert kwargs['content_type'] == 'text/plain' + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_rejects_input_not_sent_as_json_with_persistence_on( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence on, a start without a name raises a `TypeError` for an input that is not sent as JSON.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + with pytest.raises(TypeError, match='needs a JSON input'): + await Actor.start('some-actor', b'bytes') - assert run.id == 'old-run' - assert run.status == 'RUNNING' assert apify_client_async_patcher.calls['actor']['start'] == [] - [(args, kwargs)] = apify_client_async_patcher.calls['run']['resurrect'] - assert args[0].resource_id == 'old-run' - assert kwargs['memory_mbytes'] == 2048 + + +def test_persist_unnamed_child_runs_is_off_by_default(monkeypatch: pytest.MonkeyPatch) -> None: + """`Configuration.persist_unnamed_child_runs` is off unless the environment variable turns it on.""" + assert Configuration().persist_unnamed_child_runs is False + + monkeypatch.setenv('APIFY_PERSIST_UNNAMED_CHILD_RUNS', 'true') + + assert Configuration().persist_unnamed_child_runs is True @pytest.mark.parametrize( 'status', [ + pytest.param('READY', id='ready'), + pytest.param('RUNNING', id='running'), + pytest.param('SUCCEEDED', id='succeeded'), + pytest.param('FAILED', id='failed'), pytest.param('ABORTING', id='aborting'), + pytest.param('ABORTED', id='aborted'), pytest.param('TIMING-OUT', id='timing out'), + pytest.param('TIMED-OUT', id='timed out'), ], ) -async def test_named_start_resurrects_settling_run_after_it_finishes( +async def test_named_start_returns_recorded_run_in_any_status( apify_client_async_patcher: ApifyClientAsyncPatcher, status: str ) -> None: - """A recorded run still aborting or timing out is waited for, then resurrected.""" - finished_status = {'ABORTING': 'ABORTED', 'TIMING-OUT': 'TIMED-OUT'}[status] + """A recorded run is returned in the status it is in, without starting, resurrecting or waiting for a run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) - apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', finished_status)) apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'SUCCEEDED')) async with Actor: await record_child_run('scrape-eu', 'old-run') run = await Actor.start('some-actor', run_name='scrape-eu') - assert run.status == 'RUNNING' - assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 - assert len(apify_client_async_patcher.calls['run']['resurrect']) == 1 + assert run.id == 'old-run' + assert run.status == status + assert apify_client_async_patcher.calls['actor']['start'] == [] + assert apify_client_async_patcher.calls['run']['resurrect'] == [] + assert apify_client_async_patcher.calls['run']['wait_for_finish'] == [] -@pytest.mark.parametrize( - ('recorded_run', 'replaced_status'), - [ - pytest.param(make_run('old-run', 'FAILED'), 'FAILED', id='failed'), - pytest.param(None, 'LOST', id='not found'), - ], -) -async def test_named_start_replaces_failed_or_missing_run( +async def test_named_start_replaces_missing_run( apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch, - recorded_run: Run | None, - replaced_status: str, + caplog: pytest.LogCaptureFixture, ) -> None: - """A recorded run that failed or no longer exists is replaced by a new run and kept in the history.""" + """A recorded run that no longer exists is replaced by a new run under the same name, with a warning.""" monkeypatch.setattr(_child_runs, '_NOT_FOUND_GRACE_SECS', 0) apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('run', 'get', return_value=recorded_run) + apify_client_async_patcher.patch('run', 'get', return_value=None) async with Actor: await record_child_run('scrape-eu', 'old-run') run = await Actor.start('some-actor', run_name='scrape-eu') kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) + child_runs = Actor.child_runs assert run.id == 'new-run' - assert stored == { - 'scrape-eu': stored_record( - 'new-run', 'READY', history=[{'runId': 'old-run', 'status': replaced_status, 'startedAt': STARTED_AT}] - ) - } + assert stored == stored_registry({'scrape-eu': stored_record('new-run', 'READY')}) + assert child_runs.named['scrape-eu'].client.resource_id == 'new-run' + [warning] = [record for record in caplog.records if record.levelname == 'WARNING'] + assert 'Child run "scrape-eu" no longer exists' in warning.getMessage() + assert warning.__dict__['run_id'] == 'old-run' async def test_named_start_rejects_name_recorded_for_another_actor( @@ -237,7 +431,7 @@ async def test_named_start_rejects_name_recorded_for_another_actor( async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id='other-actor') - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await Actor.start('some-actor', run_name='scrape-eu') assert apify_client_async_patcher.calls['actor']['start'] == [] @@ -252,7 +446,7 @@ async def test_named_start_rejects_name_recorded_for_task( async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await Actor.start('some-actor', run_name='scrape-eu') assert apify_client_async_patcher.calls['actor']['start'] == [] @@ -340,40 +534,76 @@ async def test_named_call_streams_new_run_log_from_start(apify_client_async_patc assert apify_client_async_patcher.calls['actor']['call'] == [] -async def test_named_call_returns_succeeded_run_without_waiting( - apify_client_async_patcher: ApifyClientAsyncPatcher, +@pytest.mark.parametrize( + 'status', + [ + pytest.param('SUCCEEDED', id='succeeded'), + pytest.param('FAILED', id='failed'), + pytest.param('ABORTED', id='aborted'), + pytest.param('TIMED-OUT', id='timed out'), + ], +) +async def test_named_call_returns_finished_run_without_waiting( + apify_client_async_patcher: ApifyClientAsyncPatcher, status: str ) -> None: - """A named call whose recorded run already succeeded returns it without waiting or streaming logs.""" - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED')) + """A named call whose recorded run already finished returns it without waiting or streaming logs.""" + get_streamed_log = Mock(return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=None) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) async with Actor: await record_child_run('scrape-eu', 'old-run') run = await Actor.call('some-actor', run_name='scrape-eu') assert run.id == 'old-run' + assert run.status == status assert apify_client_async_patcher.calls['run']['wait_for_finish'] == [] + get_streamed_log.assert_not_called() -async def test_named_call_waits_for_resurrected_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A named call resurrects an aborted run with its own timeout and streams only the new log lines.""" - get_streamed_log = Mock(return_value=MagicMock()) - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTED')) +@pytest.mark.parametrize( + ('status', 'finished_status'), + [ + pytest.param('ABORTING', 'ABORTED', id='aborting'), + pytest.param('TIMING-OUT', 'TIMED-OUT', id='timing out'), + ], +) +async def test_named_call_waits_for_settling_run( + apify_client_async_patcher: ApifyClientAsyncPatcher, status: str, finished_status: str +) -> None: + """A named call whose recorded run is aborting or timing out waits for it and returns it finished.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', finished_status)) apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) - apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'SUCCEEDED')) - apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) - apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) async with Actor: await record_child_run('scrape-eu', 'old-run') - run = await Actor.call('some-actor', run_name='scrape-eu', timeout=timedelta(minutes=5)) + run = await Actor.call('some-actor', run_name='scrape-eu', logger=None) + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) - assert run.id == 'old-run' - assert run.status == 'SUCCEEDED' - assert apify_client_async_patcher.calls['actor']['start'] == [] - [(_, kwargs)] = apify_client_async_patcher.calls['run']['resurrect'] - assert kwargs['run_timeout'] == timedelta(minutes=5) - assert get_streamed_log.call_args.kwargs['from_start'] is False + assert run.status == finished_status + assert stored['named']['scrape-eu']['status'] == finished_status + assert apify_client_async_patcher.calls['run']['resurrect'] == [] + + +async def test_named_call_returns_active_run_when_wait_runs_out( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A named call whose `wait` runs out returns the run in its current status.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'RUNNING')) + + async with Actor: + run = await Actor.call('some-actor', run_name='scrape-eu', wait=timedelta(seconds=1), logger=None) + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.status == 'RUNNING' + assert stored['named']['scrape-eu']['status'] == 'RUNNING' + [(_, kwargs)] = apify_client_async_patcher.calls['run']['wait_for_finish'] + assert kwargs['wait_duration'] == timedelta(seconds=1) async def test_named_call_without_logger_only_waits(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -398,7 +628,7 @@ async def test_init_rejects_malformed_registry() -> None: """Init raises a `ValueError` naming the key when the registry in the default KVS is malformed, and tears down.""" async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value(CHILD_RUNS_KEY, {'scrape-eu': {'runId': 'old-run'}}) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'scrape-eu': {'runId': 'old-run'}})) with pytest.raises(ValueError, match=CHILD_RUNS_KEY): await Actor.init() @@ -407,6 +637,18 @@ async def test_init_rejects_malformed_registry() -> None: assert not Actor.event_manager.active +async def test_init_does_not_read_the_actor_child_runs_key() -> None: + """A value under the `__ACTOR_CHILD_RUNS` key is not read as the registry.""" + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value('__ACTOR_CHILD_RUNS', {'scrape-eu': {'runId': 'old-run'}}) + + async with Actor: + child_runs = Actor.child_runs + + assert child_runs == ChildRuns(named={}, unnamed={}) + + async def test_named_call_task_records_run_in_kvs(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """A named task call starts the task, records the run under the task ID, and waits for it.""" apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) @@ -418,7 +660,9 @@ async def test_named_call_task_records_run_in_kvs(apify_client_async_patcher: Ap stored = await kvs.get_value(CHILD_RUNS_KEY) assert run.status == 'SUCCEEDED' - assert stored == {'scrape-eu': stored_record('new-run', 'SUCCEEDED', actor_id=None, task_id='some-task')} + assert stored == stored_registry( + {'scrape-eu': stored_record('new-run', 'SUCCEEDED', actor_id=None, task_id='some-task')} + ) assert apify_client_async_patcher.calls['task']['call'] == [] @@ -437,21 +681,20 @@ async def test_named_call_task_waits_for_reattached_run(apify_client_async_patch assert apify_client_async_patcher.calls['task']['start'] == [] -async def test_named_call_task_resurrects_recorded_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A named task call resurrects an aborted run with its own options.""" +async def test_named_call_task_returns_aborted_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A named task call whose recorded run was aborted returns it without resurrecting it.""" apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) 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')) - apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'SUCCEEDED')) async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - run = await Actor.call_task('some-task', run_name='scrape-eu', memory_mbytes=2048) + run = await Actor.call_task('some-task', run_name='scrape-eu') assert run.id == 'old-run' + assert run.status == 'ABORTED' assert apify_client_async_patcher.calls['task']['start'] == [] - [(_, kwargs)] = apify_client_async_patcher.calls['run']['resurrect'] - assert kwargs['memory_mbytes'] == 2048 + assert apify_client_async_patcher.calls['run']['resurrect'] == [] async def test_named_call_task_rejects_name_recorded_for_actor( @@ -463,7 +706,7 @@ async def test_named_call_task_rejects_name_recorded_for_actor( async with Actor: await record_child_run('scrape-eu', 'old-run') - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await Actor.call_task('some-task', run_name='scrape-eu') assert apify_client_async_patcher.calls['task']['start'] == [] @@ -485,22 +728,16 @@ async def test_named_runs_forward_max_items_to_start(apify_client_async_patcher: assert task_kwargs['max_items'] == 30 -async def test_named_start_forwards_max_items_to_resurrect( - apify_client_async_patcher: ApifyClientAsyncPatcher, -) -> None: - """A named start that resurrects the recorded run passes `max_items` to it and warns about it only once.""" - 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')) +async def test_named_start_warns_about_max_items_once(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A named start with `max_items` warns about the deprecated option once, pointing at the caller.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) async with Actor: - await record_child_run('scrape-eu', 'old-run') with pytest.warns(FutureWarning, match='max_items') as warnings: await Actor.start('some-actor', run_name='scrape-eu', max_items=10) future_warnings = [warning for warning in warnings if warning.category is FutureWarning] assert [warning.filename for warning in future_warnings] == [__file__] - [(_, kwargs)] = apify_client_async_patcher.calls['run']['resurrect'] - assert kwargs['max_items'] == 10 async def test_named_start_task_records_run_in_kvs(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -513,7 +750,9 @@ async def test_named_start_task_records_run_in_kvs(apify_client_async_patcher: A stored = await kvs.get_value(CHILD_RUNS_KEY) assert run.id == 'new-run' - assert stored == {'scrape-eu': stored_record('new-run', 'READY', actor_id=None, task_id='some-task')} + assert stored == stored_registry( + {'scrape-eu': stored_record('new-run', 'READY', actor_id=None, task_id='some-task')} + ) assert apify_client_async_patcher.calls['run']['wait_for_finish'] == [] @@ -531,12 +770,12 @@ async def test_named_start_task_reuses_recorded_run(apify_client_async_patcher: async def test_name_lock_is_dropped_after_named_start(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """The per-name lock is released from the registry once no named start holds it.""" + """The per-key lock is released from the registry once no named start holds it.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) async with _ActorType() as actor: await actor.start('some-actor', run_name='scrape-eu') - assert len(actor._child_run_registry._name_locks) == 0 + assert len(actor._child_run_registry._key_locks) == 0 async def test_named_start_retries_recorded_run_not_found_yet( @@ -561,6 +800,7 @@ async def test_named_start_retries_recorded_run_not_found_yet( [ pytest.param('RUNNING', id='running'), pytest.param('SUCCEEDED', id='succeeded'), + pytest.param('FAILED', id='failed'), pytest.param('ABORTED', id='aborted'), ], ) @@ -568,52 +808,77 @@ async def test_named_start_rejects_name_recorded_with_other_input( apify_client_async_patcher: ApifyClientAsyncPatcher, status: str, ) -> None: - """Reusing a name with a different input raises instead of reattaching to, or resurrecting, the earlier run.""" + """Reusing a name with a different input raises, whatever the status of the recorded run.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) - apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) async with Actor: await record_child_run('scrape-eu', 'old-run', run_input={'since': '2025-01-01'}) - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await Actor.start('some-actor', {'since': '2026-01-01'}, run_name='scrape-eu') assert apify_client_async_patcher.calls['actor']['start'] == [] - assert apify_client_async_patcher.calls['run']['resurrect'] == [] + assert apify_client_async_patcher.calls['run']['get'] == [] @pytest.mark.parametrize( - ('recorded_actor_id', 'recorded_input'), + ('recorded_options', 'call_options'), [ - pytest.param('other-actor', None, id='other actor'), - pytest.param('some-actor', {'since': '2025-01-01'}, id='other input'), + pytest.param({}, {'memory_mbytes': 2048}, id='option added'), + pytest.param({'memory': 1024}, {'memory_mbytes': 2048}, id='option changed'), + pytest.param({'build': 'latest'}, {}, id='option removed'), ], ) -async def test_named_start_replaces_run_recorded_for_other_request( +async def test_named_start_rejects_name_recorded_with_other_options( apify_client_async_patcher: ApifyClientAsyncPatcher, - recorded_actor_id: str, - recorded_input: Any, + recorded_options: dict[str, Any], + call_options: dict[str, Any], ) -> None: - """A failed run recorded for another Actor or input is replaced, and the name takes the new run's checksum.""" + """Reusing a name with different run options raises.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'FAILED')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'RUNNING')) async with Actor: - await record_child_run('scrape-eu', 'old-run', actor_id=recorded_actor_id, run_input=recorded_input) - run = await Actor.start('some-actor', {'since': '2026-01-01'}, run_name='scrape-eu') - kvs = await Actor.open_key_value_store() - stored = await kvs.get_value(CHILD_RUNS_KEY) + await record_child_run('scrape-eu', 'old-run', options=recorded_options) + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): + await Actor.start('some-actor', run_name='scrape-eu', **call_options) - assert run.id == 'new-run' - assert stored == { - 'scrape-eu': stored_record( - 'new-run', - 'READY', - run_input={'since': '2026-01-01'}, - history=[{'runId': 'old-run', 'status': 'FAILED', 'startedAt': STARTED_AT}], - ) + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +async def test_named_start_reuses_run_recorded_with_same_options( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A call with the recorded run options returns the recorded run, also with another token and `wait`.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED')) + recorded_options = { + 'build': 'beta', + 'forcePermissionLevel': 'LIMITED_PERMISSIONS', + 'maxTotalChargeUsd': 1.5, + 'memory': 2048, + 'restartOnError': True, + 'timeout': 90, + 'webhooks': [{'eventTypes': ['ACTOR.RUN.SUCCEEDED'], 'requestUrl': 'https://example.com/hook'}], } + async with Actor: + await record_child_run('scrape-eu', 'old-run', options=recorded_options) + run = await Actor.call( + 'some-actor', + run_name='scrape-eu', + build='beta', + force_permission_level='LIMITED_PERMISSIONS', + max_total_charge_usd=Decimal('1.50'), + memory_mbytes=2048, + restart_on_error=True, + timeout=timedelta(seconds=90), + webhooks=[Webhook(event_types=['ACTOR.RUN.SUCCEEDED'], request_url='https://example.com/hook')], + token='other-token', + wait=timedelta(seconds=5), + ) + + assert run.id == 'old-run' + async def test_named_start_ignores_input_key_order(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """An input equal to the recorded one up to key order reattaches to the recorded run.""" @@ -655,30 +920,160 @@ def test_checksum_matches_js_sdk(request_kwargs: dict[str, Any], expected: str) assert checksum_request(**request_kwargs) == expected -async def test_reattached_run_status_is_recorded(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """Reattaching to a recorded run stores its current status.""" - apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED')) +def test_checksum_hashes_canonical_json_of_the_request() -> None: + """The checksum is the SHA-256 of the request as canonical JSON, with sorted keys and no whitespace.""" + checksum = checksum_request( + actor_id='some-actor', + run_input={'b': [1.0, 2.5, 1e21, 1e-7], 'a': '\u00e9"\n'}, + options={'timeout': 60, 'memory': 256}, + ) + canonical = ( + '{"id":"some-actor","input":{"a":"\u00e9\\"\\n","b":[1,2.5,1e+21,1e-7]},' + '"options":{"memory":256,"timeout":60},"type":"actor"}' + ) - async with Actor: - await record_child_run('scrape-eu', 'old-run') - await Actor.start('some-actor', run_name='scrape-eu') - kvs = await Actor.open_key_value_store() - stored = await kvs.get_value(CHILD_RUNS_KEY) + assert checksum == hashlib.sha256(canonical.encode()).hexdigest() - assert stored == {'scrape-eu': stored_record('old-run', 'SUCCEEDED')} +@pytest.mark.parametrize( + ('run_input', 'canonical_input'), + [ + pytest.param({'n': 0.0}, '{"n":0}', id='zero'), + pytest.param({'n': -0.5}, '{"n":-0.5}', id='negative fraction'), + pytest.param({'n': 0.001}, '{"n":0.001}', id='small fraction'), + pytest.param({'n': -12}, '{"n":-12}', id='negative integer'), + pytest.param({'on': False, 'off': None}, '{"off":null,"on":false}', id='false and null'), + pytest.param( + {'\ufb33': 1, '\U0001f600': 2}, '{"\U0001f600":2,"\ufb33":1}', id='keys sorted by UTF-16 code units' + ), + ], +) +def test_checksum_serializes_json_values_canonically(run_input: Any, canonical_input: str) -> None: + """The checksum writes numbers, literals and object keys the way RFC 8785 defines.""" + canonical = f'{{"id":"some-actor","input":{canonical_input},"type":"actor"}}' -async def test_named_call_records_finished_status(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A named call stores the status of the run once it finishes.""" - apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'FAILED')) + assert ( + checksum_request(actor_id='some-actor', run_input=run_input) == hashlib.sha256(canonical.encode()).hexdigest() + ) - async with Actor: + +def test_checksum_accepts_an_empty_content_type() -> None: + """An empty content type counts as not set, the same as in the client.""" + assert checksum_request(actor_id='some-actor', run_input={'a': 1}, content_type='') == checksum_request( + actor_id='some-actor', run_input={'a': 1} + ) + + +@pytest.mark.parametrize( + ('first_input', 'second_input'), + [ + pytest.param({'count': 1}, {'count': 1.0}, id='integer and equal float'), + pytest.param({'a': 1, 'b': 2}, {'b': 2, 'a': 1}, id='key order'), + pytest.param({'price': Decimal('1.50')}, {'price': '1.50'}, id='value the client sends as a string'), + ], +) +def test_checksum_is_equal_for_inputs_sent_as_the_same_json(first_input: Any, second_input: Any) -> None: + """Two inputs that the client sends as the same JSON document have the same checksum.""" + first = checksum_request(actor_id='some-actor', run_input=first_input) + second = checksum_request(actor_id='some-actor', run_input=second_input) + + assert first == second + + +def test_checksum_differs_for_actor_and_task_with_the_same_id() -> None: + """An Actor and a task with the same ID have different checksums.""" + assert checksum_request(actor_id='some-id') != checksum_request(task_id='some-id') + + +def test_checksum_ignores_json_content_type_and_empty_options() -> None: + """A JSON content type and no run options leave the checksum as it is without them.""" + plain = checksum_request(actor_id='some-actor', run_input={'a': 1}) + with_content_type = checksum_request( + actor_id='some-actor', run_input={'a': 1}, content_type='application/json; charset=utf-8', options={} + ) + + assert plain == with_content_type + + +@pytest.mark.parametrize( + ('run_input', 'content_type'), + [ + pytest.param('{"a": 1}', None, id='string'), + pytest.param(b'{"a": 1}', None, id='bytes'), + pytest.param(io.BytesIO(b'{"a": 1}'), None, id='stream'), + pytest.param({'a': 1}, 'text/plain', id='other content type'), + ], +) +def test_checksum_rejects_input_not_sent_as_json(run_input: Any, content_type: str | None) -> None: + """An input that the client does not serialize to JSON cannot be hashed.""" + with pytest.raises(TypeError, match='needs a JSON input'): + checksum_request(actor_id='some-actor', run_input=run_input, content_type=content_type) + + +def test_checksum_run_options_use_the_api_names_and_values() -> None: + """The hashed run options carry the names and values of the API, and the options that are not set are left out.""" + options = checksum_run_options( + build='beta', + max_items=10, + max_total_charge_usd=Decimal('2.50'), + restart_on_error=False, + memory_mbytes=1024, + timeout=timedelta(minutes=2), + force_permission_level='FULL_PERMISSIONS', + webhooks=to_client_representations( + [Webhook(event_types=['ACTOR.RUN.FAILED'], request_url='https://example.com/hook')] + ), + ) + + assert options == { + 'build': 'beta', + 'forcePermissionLevel': 'FULL_PERMISSIONS', + 'maxItems': 10, + 'maxTotalChargeUsd': 2.5, + 'memory': 1024, + 'restartOnError': False, + 'timeout': 120, + 'webhooks': [{'eventTypes': ['ACTOR.RUN.FAILED'], 'requestUrl': 'https://example.com/hook'}], + } + assert checksum_run_options() == {} + assert checksum_run_options(timeout='inherit') == {'timeout': 'inherit'} + + +async def test_named_start_rejects_input_not_sent_as_json(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A named start with an input that is not sent as JSON raises a `TypeError` and starts no run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + with pytest.raises(TypeError, match='needs a JSON input'): + await Actor.start('some-actor', 'plain text', run_name='scrape-eu') + + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +async def test_reattached_run_status_is_recorded(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """Reattaching to a recorded run stores its current status.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED')) + + async with Actor: + await record_child_run('scrape-eu', 'old-run') + await Actor.start('some-actor', run_name='scrape-eu') + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert stored == stored_registry({'scrape-eu': stored_record('old-run', 'SUCCEEDED')}) + + +async def test_named_call_records_finished_status(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A named call stores the status of the run once it finishes.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'FAILED')) + + async with Actor: await Actor.call('some-actor', run_name='scrape-eu', logger=None) kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored == {'scrape-eu': stored_record('new-run', 'FAILED')} + assert stored == stored_registry({'scrape-eu': stored_record('new-run', 'FAILED')}) async def test_child_runs_is_empty_without_named_runs(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -687,7 +1082,7 @@ async def test_child_runs_is_empty_without_named_runs(apify_client_async_patcher async with Actor: await Actor.start('some-actor') - assert Actor.child_runs == {} + assert Actor.child_runs == ChildRuns(named={}, unnamed={}) def test_child_runs_requires_initialized_actor() -> None: @@ -697,38 +1092,64 @@ def test_child_runs_requires_initialized_actor() -> None: async def test_child_runs_includes_runs_recorded_before_init() -> None: - """Init loads the runs recorded by an earlier attempt, so `Actor.child_runs` has a client for each of them.""" + """Init loads the runs recorded by an earlier process, so `Actor.child_runs` has an entry for each of them.""" async with Actor: kvs = await Actor.open_key_value_store() await kvs.set_value( CHILD_RUNS_KEY, - { - 'scrape-eu': stored_record('eu-run', 'RUNNING'), - 'scrape-us': stored_record('us-run', 'FAILED', actor_id=None, task_id='some-task'), - }, + stored_registry( + { + 'scrape-eu': stored_record('eu-run', 'RUNNING'), + 'scrape-us': stored_record( + 'us-run', 'FAILED', run_name='scrape-us', actor_id=None, task_id='some-task' + ), + } + ), ) async with Actor: child_runs = Actor.child_runs - assert {name: run_client.resource_id for name, run_client in child_runs.items()} == { + assert {name: child_run.client.resource_id for name, child_run in child_runs.named.items()} == { 'scrape-eu': 'eu-run', 'scrape-us': 'us-run', } + assert child_runs.named['scrape-us'].record.status == 'FAILED' + assert child_runs.unnamed == {} -async def test_child_runs_includes_run_started_in_this_attempt( +async def test_child_runs_includes_run_started_in_this_process( apify_client_async_patcher: ApifyClientAsyncPatcher, ) -> None: - """A run started by a named start shows up in `Actor.child_runs` right away, pointing to the current run.""" + """A run started by a named start shows up in `Actor.child_runs` right away, with its record and a client.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) async with Actor: - await Actor.start('some-actor', run_name='scrape-eu') + await Actor.start('some-actor', run_name='scrape-eu', abort_with_parent=True) child_runs = Actor.child_runs - assert child_runs.keys() == {'scrape-eu'} - assert child_runs['scrape-eu'].resource_id == 'new-run' + assert child_runs.named.keys() == {'scrape-eu'} + record, client = child_runs.named['scrape-eu'] + assert client.resource_id == 'new-run' + assert record == ChildRunRecord( + run_id='new-run', + run_name='scrape-eu', + status='READY', + checksum=checksum_request(actor_id='some-actor'), + abort_with_parent=True, + ) + + +async def test_child_runs_record_is_read_only(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """The record of a child run cannot be changed, so the registry keeps its values.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + await Actor.start('some-actor', run_name='scrape-eu') + record = Actor.child_runs.named['scrape-eu'].record + with pytest.raises(ValidationError, match='frozen'): + record.status = 'SUCCEEDED' # ty: ignore[invalid-assignment] + assert Actor.child_runs.named['scrape-eu'].record.status == 'READY' async def test_child_runs_uses_client_of_named_start( @@ -754,8 +1175,8 @@ def recording_new_client(self: _ActorType, **kwargs: Any) -> ApifyClientAsync: custom_http_client = clients_by_token['custom-token']._http_client assert custom_http_client is not default_http_client - assert child_runs['custom']._http_client is custom_http_client - assert child_runs['recorded']._http_client is default_http_client + assert child_runs.named['custom'].client._http_client is custom_http_client + assert child_runs.named['recorded'].client._http_client is default_http_client async def test_child_runs_keeps_client_of_name_after_rejected_reuse( @@ -767,12 +1188,12 @@ async def test_child_runs_keeps_client_of_name_after_rejected_reuse( async with Actor: await Actor.start('some-actor', {'since': '2025-01-01'}, run_name='scrape-eu') - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await Actor.start('some-actor', {'since': '2026-01-01'}, run_name='scrape-eu', token='other-token') child_runs = Actor.child_runs default_http_client = Actor.apify_client._http_client - assert child_runs['scrape-eu']._http_client is default_http_client + assert child_runs.named['scrape-eu'].client._http_client is default_http_client async def test_child_runs_keeps_client_of_name_after_failed_lookup( @@ -789,7 +1210,7 @@ async def test_child_runs_keeps_client_of_name_after_failed_lookup( child_runs = Actor.child_runs default_http_client = Actor.apify_client._http_client - assert child_runs['scrape-eu']._http_client is default_http_client + assert child_runs.named['scrape-eu'].client._http_client is default_http_client @pytest.mark.parametrize( @@ -801,16 +1222,16 @@ 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_requires_tracked_run( apify_client_async_patcher: ApifyClientAsyncPatcher, method: str ) -> None: - """`abort_with_parent` without a `run_name` raises before any run is started.""" + """With persistence off, `abort_with_parent` without a `run_name` raises before any run is started.""" for resource in ('actor', 'task'): apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) apify_client_async_patcher.patch(resource, 'call', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - with pytest.raises(ValueError, match='requires `run_name`'): + with pytest.raises(ValueError, match=r'requires `run_name` or `Configuration\.persist_unnamed_child_runs`'): await getattr(Actor, method)('some-id', abort_with_parent=True) for resource in ('actor', 'task'): @@ -818,6 +1239,47 @@ async def test_abort_with_parent_requires_run_name( assert apify_client_async_patcher.calls[resource]['call'] == [] +@pytest.mark.parametrize( + 'abort_with_parent', + [ + pytest.param(False, id='false'), + pytest.param(None, id='none'), + ], +) +async def test_unnamed_start_without_abort_with_parent_is_not_tracked( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, abort_with_parent: bool | None +) -> None: + """With persistence off, a start without a name that does not ask for the abort starts an untracked run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + run = await Actor.start('some-actor', abort_with_parent=abort_with_parent) + child_runs = Actor.child_runs + + assert run.id == 'new-run' + assert child_runs == ChildRuns(named={}, unnamed={}) + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_child_run_is_aborted_with_parent( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """With persistence on, a run started without a name and with `abort_with_parent` is 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.unnamed.values() + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + + assert child_run.record.abort_with_parent is True + [(args, kwargs)] = apify_client_async_patcher.calls['run']['abort'] + assert args[0].resource_id == 'new-run' + assert kwargs == {'gracefully': True} + + async def test_named_start_records_abort_with_parent(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """A named start with `abort_with_parent` records the flag with the run.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) @@ -827,7 +1289,7 @@ async def test_named_start_records_abort_with_parent(apify_client_async_patcher: kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored['scrape-eu']['abortWithParent'] is True + assert stored['named']['scrape-eu']['abortWithParent'] is True async def test_named_call_task_records_abort_with_parent( @@ -842,23 +1304,53 @@ async def test_named_call_task_records_abort_with_parent( kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored['scrape-eu']['abortWithParent'] is True + assert stored['named']['scrape-eu']['abortWithParent'] is True -async def test_reattach_replaces_recorded_abort_with_parent( - apify_client_async_patcher: ApifyClientAsyncPatcher, +@pytest.mark.parametrize( + ('recorded', 'passed', 'expected'), + [ + pytest.param(False, True, True, id='true replaces false'), + pytest.param(True, False, False, id='false replaces true'), + pytest.param(True, None, True, id='none keeps true'), + pytest.param(False, None, False, id='none keeps false'), + ], +) +async def test_recorded_abort_with_parent_follows_the_latest_call( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, recorded: bool, passed: bool | None, expected: bool ) -> None: - """Reattaching under a name records the `abort_with_parent` value of the latest call.""" + """A call under a recorded key replaces the recorded `abort_with_parent` with `True` or `False`, not `None`.""" apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'RUNNING')) async with Actor: - await record_child_run('scrape-eu', 'old-run') - await Actor.start('some-actor', run_name='scrape-eu', abort_with_parent=True) kvs = await Actor.open_key_value_store() + record = stored_record('old-run', 'RUNNING', abort_with_parent=recorded) + 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=passed) + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert stored['named']['scrape-eu']['runId'] == 'old-run' + assert stored['named']['scrape-eu']['abortWithParent'] is expected + + +async def test_run_replacing_a_missing_one_keeps_recorded_abort_with_parent( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """A run that replaces a missing one keeps the recorded `abort_with_parent` when the call passes `None`.""" + monkeypatch.setattr(_child_runs, '_NOT_FOUND_GRACE_SECS', 0) + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=None) + + 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') stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored['scrape-eu']['runId'] == 'old-run' - assert stored['scrape-eu']['abortWithParent'] is True + assert stored == stored_registry({'scrape-eu': stored_record('new-run', 'READY', abort_with_parent=True)}) async def test_aborting_event_aborts_marked_child_runs( @@ -882,18 +1374,16 @@ async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value( - CHILD_RUNS_KEY, - { - name: stored_record(run_id, 'RUNNING', abort_with_parent=marked) - for name, run_id, marked in [ - ('running', 'running-run', True), - ('ready', 'ready-run', True), - ('finished', 'finished-run', True), - ('unmarked', 'unmarked-run', False), - ] - }, - ) + records = { + name: stored_record(run_id, 'RUNNING', run_name=name, abort_with_parent=marked) + for name, run_id, marked in [ + ('running', 'running-run', True), + ('ready', 'ready-run', True), + ('finished', 'finished-run', True), + ('unmarked', 'unmarked-run', False), + ] + } + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(records)) 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() @@ -907,6 +1397,111 @@ async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: assert 'Aborted child run "finished"' not in caplog.text +async def test_aborting_event_flags_the_child_runs_it_aborts( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """On `ABORTING`, the runs this abort stops get `abortedWithParent`, and the others do not.""" + statuses_after_abort = { + 'running-run': 'ABORTING', + 'ready-run': 'ABORTED', + 'finished-run': 'SUCCEEDED', + 'aborted-earlier-run': 'ABORTED', + } + + async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: + return make_run(run_client.resource_id, statuses_after_abort[run_client.resource_id]) + + apify_client_async_patcher.patch('run', 'abort', replacement_method=abort_run) + + async with Actor: + kvs = await seed_registry( + { + 'running': stored_record('running-run', 'RUNNING', run_name='running', abort_with_parent=True), + 'ready': stored_record('ready-run', 'READY', run_name='ready', abort_with_parent=True), + 'finished': stored_record('finished-run', 'RUNNING', run_name='finished', abort_with_parent=True), + 'aborted-earlier': stored_record( + 'aborted-earlier-run', 'ABORTED', run_name='aborted-earlier', abort_with_parent=True + ), + 'unmarked': stored_record('unmarked-run', 'RUNNING', run_name='unmarked'), + } + ) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + flags = {name: (record['status'], record['abortedWithParent']) for name, record in stored['named'].items()} + assert flags == { + 'running': ('ABORTING', True), + 'ready': ('ABORTED', True), + 'finished': ('SUCCEEDED', False), + 'aborted-earlier': ('ABORTED', False), + 'unmarked': ('RUNNING', False), + } + + +async def test_aborting_event_flags_the_child_runs_before_it_sends_the_requests( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """The runs to abort are flagged in the default KVS before the abort requests are sent.""" + stored_during_abort = list[Any]() + + async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: + kvs = await Actor.open_key_value_store() + stored_during_abort.append(await kvs.get_value(CHILD_RUNS_KEY)) + return make_run(run_client.resource_id, 'ABORTING') + + apify_client_async_patcher.patch('run', 'abort', replacement_method=abort_run) + + async with Actor: + await seed_registry({'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + + [stored] = stored_during_abort + assert stored['named']['scrape-eu']['abortedWithParent'] is True + + +async def test_aborting_event_writes_nothing_without_marked_child_runs(apify_event_manager: ApifyEventManager) -> None: + """On `ABORTING`, an Actor run without child runs to abort leaves the default KVS without a registry.""" + async with Actor: + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert stored is None + + +async def test_start_in_flight_during_aborting_is_flagged_as_aborted_with_parent() -> None: + """A marked run whose start was in flight when the parent got `ABORTING` is recorded as aborted with the parent.""" + client = Mock() + client.run.return_value.abort = AsyncMock(return_value=make_run('new-run', 'ABORTING')) + started = asyncio.Event() + release = asyncio.Event() + + async def start_run() -> Run: + started.set() + await release.wait() + return make_run('new-run', 'READY') + + async with Actor: + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + key = ChildRunKey('named', 'scrape-eu') + start_task = asyncio.create_task( + registry.find_or_start(key, checksum='checksum', client=client, start_run=start_run, abort_with_parent=True) + ) + await started.wait() + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0) + release.set() + await asyncio.gather(start_task, abort_task) + record = registry.child_runs(client).named['scrape-eu'].record + + assert record.aborted_with_parent is True + assert record.status == 'ABORTING' + + async def test_aborting_event_skips_a_child_run_that_no_longer_exists( apify_client_async_patcher: ApifyClientAsyncPatcher, caplog: pytest.LogCaptureFixture, @@ -918,7 +1513,8 @@ async def test_aborting_event_skips_a_child_run_that_no_longer_exists( async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value(CHILD_RUNS_KEY, {'gone': stored_record('gone-run', 'RUNNING', abort_with_parent=True)}) + record = stored_record('gone-run', 'RUNNING', run_name='gone', abort_with_parent=True) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'gone': record})) 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() @@ -943,10 +1539,11 @@ async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value( - CHILD_RUNS_KEY, - {name: stored_record(f'{name}-run', 'RUNNING', abort_with_parent=True) for name in ['broken', 'healthy']}, - ) + records = { + name: stored_record(f'{name}-run', 'RUNNING', run_name=name, abort_with_parent=True) + for name in ['broken', 'healthy'] + } + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(records)) 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() @@ -965,13 +1562,12 @@ async def test_child_run_is_aborted_with_the_client_it_was_started_with() -> Non async with Actor: registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() await registry.find_or_start( - 'scrape-eu', - actor_id='some-actor', - run_input=None, + ChildRunKey('named', 'scrape-eu'), + checksum='checksum', client=child_client, start_run=AsyncMock(return_value=make_run('new-run', 'READY')), - resurrect_run=AsyncMock(), abort_with_parent=True, ) await registry.abort_runs_with_parent(default_client) @@ -990,16 +1586,16 @@ async def test_rejected_named_start_keeps_the_client_used_to_abort() -> None: async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value(CHILD_RUNS_KEY, {'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + record = stored_record('old-run', 'RUNNING', abort_with_parent=True) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'scrape-eu': record})) registry = ChildRunRegistry(Actor.open_key_value_store) - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + await registry.load() + with pytest.raises(ValueError, match='already used for a different Actor, task, input or run options'): await registry.find_or_start( - 'scrape-eu', - actor_id='other-actor', - run_input=None, + ChildRunKey('named', 'scrape-eu'), + checksum='other-checksum', client=other_client, start_run=AsyncMock(), - resurrect_run=AsyncMock(), ) await registry.abort_runs_with_parent(default_client) @@ -1021,14 +1617,13 @@ async def start_run() -> Run: async with Actor: registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() start_task = asyncio.create_task( registry.find_or_start( - 'scrape-eu', - actor_id='some-actor', - run_input=None, + ChildRunKey('named', 'scrape-eu'), + checksum='checksum', client=client, start_run=start_run, - resurrect_run=AsyncMock(), abort_with_parent=True, ) ) @@ -1042,10 +1637,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 key while the parent is aborted returns 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() @@ -1058,24 +1654,21 @@ async def start_run() -> Run: async with Actor: registry = ChildRunRegistry(Actor.open_key_value_store) - options: dict[str, Any] = { - 'actor_id': 'some-actor', - 'run_input': None, - 'client': client, - 'resurrect_run': AsyncMock(), - 'abort_with_parent': True, - } - first_start = asyncio.create_task(registry.find_or_start('scrape-eu', start_run=start_run, **options)) + await registry.load() + key = ChildRunKey('named', 'scrape-eu') + options: dict[str, Any] = {'checksum': 'checksum', 'client': client, 'abort_with_parent': True} + first_start = asyncio.create_task(registry.find_or_start(key, start_run=start_run, **options)) await started.wait() - queued_start = asyncio.create_task(registry.find_or_start('scrape-eu', start_run=queued_start_run, **options)) + queued_start = asyncio.create_task(registry.find_or_start(key, start_run=queued_start_run, **options)) await asyncio.sleep(0) abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) await asyncio.sleep(0) release.set() await asyncio.gather(first_start, abort_task) - with pytest.raises(RuntimeError, match='being aborted'): - await queued_start + queued_run, is_new = await queued_start + assert queued_run.id == 'new-run' + assert is_new is False queued_start_run.assert_not_awaited() client.run.return_value.abort.assert_awaited_once_with(gracefully=True) @@ -1110,28 +1703,104 @@ 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_marked_call_once_aborting_returns_the_recorded_run( 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 call with `abort_with_parent` under a recorded key waits for the child to be aborted.""" 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')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'ABORTED')) async with Actor: kvs = await Actor.open_key_value_store() - await kvs.set_value(CHILD_RUNS_KEY, {'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + 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() 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, logger=None) + assert run.id == 'old-run' + 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'] == [] +async def test_recorded_mark_blocks_a_run_replacing_a_missing_one_once_aborting( + apify_client_async_patcher: ApifyClientAsyncPatcher, + apify_event_manager: ApifyEventManager, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """After `ABORTING`, a call that would replace a missing run marked `abort_with_parent` raises.""" + monkeypatch.setattr(_child_runs, '_NOT_FOUND_GRACE_SECS', 0) + not_found = NotFoundError(Mock(status_code=404, json=Mock(return_value={})), 1, method='POST') + apify_client_async_patcher.patch('run', 'abort', replacement_method=Mock(side_effect=not_found)) + apify_client_async_patcher.patch('run', 'get', return_value=None) + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + 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() + 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', run_name='scrape-eu') + + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +async def test_abort_of_child_runs_stops_waiting_after_the_time_limit( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """An abort request that does not return is waited for only up to the time limit, with a warning.""" + monkeypatch.setattr(_child_runs, '_ABORT_WITH_PARENT_TIMEOUT', timedelta(milliseconds=50)) + never = asyncio.Event() + + async def hanging_abort(**_kwargs: Any) -> Run: + await never.wait() + return make_run('new-run', 'ABORTING') + + client = Mock() + client.run.return_value.abort = hanging_abort + + async with Actor: + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + await registry.find_or_start( + ChildRunKey('named', 'scrape-eu'), + checksum='checksum', + client=client, + start_run=AsyncMock(return_value=make_run('new-run', 'READY')), + abort_with_parent=True, + ) + await asyncio.wait_for(registry.abort_runs_with_parent(client), timeout=5) + + assert 'Aborting the child runs with the parent did not finish in 0.05 seconds' in caplog.text + + +async def test_exit_waits_for_the_abort_of_child_runs( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """`Actor.exit()` waits for the abort of the child runs longer than for the event listeners.""" + finished_aborts = list[str]() + + async def slow_abort(run_client: Any, **_kwargs: Any) -> Run: + await asyncio.sleep(0.3) + finished_aborts.append(run_client.resource_id) + return make_run(run_client.resource_id, 'ABORTING') + + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'abort', replacement_method=slow_abort) + + async with Actor(event_listeners_timeout=timedelta(milliseconds=50)): + await Actor.start('some-actor', run_name='scrape-eu', abort_with_parent=True) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + + assert finished_aborts == ['new-run'] + + async def test_named_start_without_abort_with_parent_is_not_blocked_once_aborting( apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager ) -> None: @@ -1190,7 +1859,7 @@ async def test_removing_all_aborting_listeners_keeps_aborting_child_runs( async def test_named_run_warns_experimental( apify_client_async_patcher: ApifyClientAsyncPatcher, method_name: str ) -> None: - """A run started with `run_name` warns that named child runs are experimental, pointing at the caller.""" + """A run started with `run_name` warns that tracked child runs are experimental, pointing at the caller.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) @@ -1206,7 +1875,7 @@ async def test_named_run_warns_experimental( async def test_unnamed_start_does_not_warn_experimental(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A run started without `run_name` emits no experimental warning.""" + """With persistence off, a run started without `run_name` emits no experimental warning.""" apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) async with Actor: @@ -1215,10 +1884,651 @@ async def test_unnamed_start_does_not_warn_experimental(apify_client_async_patch await Actor.start('some-actor') +@pytest.mark.usefixtures('persist_unnamed_child_runs') +async def test_unnamed_start_warns_experimental_with_persistence_on( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With persistence on, a run started without `run_name` warns that tracked child runs are experimental.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + with pytest.warns(UserWarning, match='experimental') as warnings: + await Actor.start('some-actor') + + assert [warning.filename for warning in warnings] == [__file__] + + async def test_child_runs_warns_experimental() -> None: - """Accessing `Actor.child_runs` warns that named child runs are experimental, pointing at the caller.""" + """Accessing `Actor.child_runs` warns that tracked child runs are experimental, pointing at the caller.""" async with Actor: with pytest.warns(UserWarning, match='experimental') as warnings: _ = Actor.child_runs assert [warning.filename for warning in warnings] == [__file__] + + +@pytest.mark.parametrize( + ('recorded', 'passed'), + [ + pytest.param(True, None, id='recorded'), + pytest.param(False, True, id='passed by the call'), + ], +) +async def test_child_run_aborted_with_parent_is_resurrected( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, recorded: bool, passed: bool | None +) -> None: + """A call resurrects a run that was aborted with the parent and is marked `resurrect_with_parent`.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + 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')) + record = stored_record( + 'old-run', 'ABORTING', abort_with_parent=True, resurrect_with_parent=recorded, aborted_with_parent=True + ) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + run = await Actor.start('some-actor', run_name='scrape-eu', resurrect_with_parent=passed) + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.id == 'old-run' + assert run.status == 'RUNNING' + [(args, kwargs)] = apify_client_async_patcher.calls['run']['resurrect'] + assert args[0].resource_id == 'old-run' + assert kwargs == {} + assert apify_client_async_patcher.calls['actor']['start'] == [] + assert stored == stored_registry( + {'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True, resurrect_with_parent=True)} + ) + + +@pytest.mark.parametrize( + ('recorded', 'passed', 'aborted_with_parent'), + [ + pytest.param(False, None, True, id='not marked'), + pytest.param(True, False, True, id='turned off by the call'), + pytest.param(True, None, False, id='aborted by someone else'), + ], +) +async def test_aborted_child_run_is_not_resurrected( + apify_client_async_patcher: ApifyClientAsyncPatcher, + *, + recorded: bool, + passed: bool | None, + aborted_with_parent: bool, +) -> None: + """An aborted run is returned `ABORTED` unless it was aborted with the parent and is marked for resurrection.""" + 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')) + record = stored_record( + 'old-run', + 'ABORTED', + abort_with_parent=True, + resurrect_with_parent=recorded, + aborted_with_parent=aborted_with_parent, + ) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + run = await Actor.start('some-actor', run_name='scrape-eu', resurrect_with_parent=passed) + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.status == 'ABORTED' + assert apify_client_async_patcher.calls['run']['resurrect'] == [] + assert stored['named']['scrape-eu']['abortedWithParent'] is aborted_with_parent + + +async def test_child_run_still_aborting_is_resurrected_after_it_is_aborted( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A run aborted with the parent that is still `ABORTING` is waited for and then resurrected.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'ABORTED')) + apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) + record = stored_record( + 'old-run', 'ABORTING', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + await seed_registry({'scrape-eu': record}) + run = await Actor.start('some-actor', run_name='scrape-eu') + + assert run.status == 'RUNNING' + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 + assert len(apify_client_async_patcher.calls['run']['resurrect']) == 1 + + +@pytest.mark.parametrize( + 'status', + [ + pytest.param('RUNNING', id='running'), + pytest.param('SUCCEEDED', id='succeeded'), + pytest.param('FAILED', id='failed'), + ], +) +async def test_child_run_not_aborted_after_all_loses_the_flag( + apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +) -> None: + """A run flagged as aborted with the parent that is in another status is returned as is, without the flag.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) + apify_client_async_patcher.patch('run', 'resurrect', return_value=make_run('old-run', 'RUNNING')) + record = stored_record( + 'old-run', 'RUNNING', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + run = await Actor.start('some-actor', run_name='scrape-eu') + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.status == status + assert apify_client_async_patcher.calls['run']['resurrect'] == [] + assert stored['named']['scrape-eu']['abortedWithParent'] is False + + +async def test_process_that_aborts_the_child_runs_does_not_resurrect_them( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """After `ABORTING`, a call in the same process returns the aborted run and does not resurrect it.""" + 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')) + record = stored_record('old-run', 'RUNNING', abort_with_parent=True, resurrect_with_parent=True) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + run = await Actor.start('some-actor', run_name='scrape-eu') + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.status == 'ABORTED' + assert apify_client_async_patcher.calls['run']['resurrect'] == [] + assert stored['named']['scrape-eu']['abortedWithParent'] is True + + +async def test_process_started_during_the_abort_does_not_resurrect_the_child_runs() -> None: + """A process that finds this Actor run `ABORTING` on the platform does not resurrect, and starts no marked run.""" + client = Mock() + client.run.return_value.get = AsyncMock(return_value=make_run('old-run', 'ABORTED')) + client.run.return_value.resurrect = AsyncMock(return_value=make_run('old-run', 'RUNNING')) + is_parent_aborting = AsyncMock(return_value=True) + start_run = AsyncMock(return_value=make_run('new-run', 'READY')) + record = stored_record( + 'old-run', 'ABORTING', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + await seed_registry({'scrape-eu': record}) + registry = ChildRunRegistry(Actor.open_key_value_store, is_parent_aborting=is_parent_aborting) + await registry.load() + run, _ = await registry.find_or_start( + ChildRunKey('named', 'scrape-eu'), checksum=record['checksum'], client=client, start_run=start_run + ) + with pytest.raises(RuntimeError, match='being aborted'): + await registry.find_or_start( + ChildRunKey('named', 'scrape-us'), + checksum='checksum', + client=client, + start_run=start_run, + abort_with_parent=True, + ) + + assert run.status == 'ABORTED' + client.run.return_value.resurrect.assert_not_awaited() + start_run.assert_not_awaited() + is_parent_aborting.assert_awaited_once() + + +async def test_run_status_is_asked_once_before_the_first_resurrection() -> None: + """The registry asks whether the parent is being aborted once, and only when it is about to resurrect a run.""" + client = Mock() + client.run.return_value.get = AsyncMock(return_value=make_run('old-run', 'ABORTED')) + client.run.return_value.resurrect = AsyncMock(return_value=make_run('old-run', 'RUNNING')) + is_parent_aborting = AsyncMock(return_value=False) + flags: dict[str, Any] = {'abort_with_parent': True, 'resurrect_with_parent': True, 'aborted_with_parent': True} + records = { + 'scrape-eu': stored_record('eu-run', 'ABORTED', **flags), + 'scrape-us': stored_record('us-run', 'ABORTED', run_name='scrape-us', **flags), + 'scrape-asia': stored_record('asia-run', 'SUCCEEDED', run_name='scrape-asia'), + } + + async with Actor: + await seed_registry(records) + registry = ChildRunRegistry(Actor.open_key_value_store, is_parent_aborting=is_parent_aborting) + await registry.load() + options: dict[str, Any] = {'checksum': records['scrape-eu']['checksum'], 'client': client} + await registry.find_or_start(ChildRunKey('named', 'scrape-asia'), start_run=AsyncMock(), **options) + is_parent_aborting.assert_not_awaited() + await registry.find_or_start(ChildRunKey('named', 'scrape-eu'), start_run=AsyncMock(), **options) + await registry.find_or_start(ChildRunKey('named', 'scrape-us'), start_run=AsyncMock(), **options) + + is_parent_aborting.assert_awaited_once() + assert client.run.return_value.resurrect.await_count == 2 + + +async def test_actor_reports_its_own_run_as_aborting( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """On the platform, the Actor reads from the API whether its own run is being gracefully aborted.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('parent-run', 'ABORTING')) + + async with Actor: + assert await Actor._is_run_aborting() is False + monkeypatch.setattr(Actor.configuration, 'is_at_home', True) + monkeypatch.setattr(Actor.configuration, 'actor_run_id', 'parent-run') + assert await Actor._is_run_aborting() is True + + [(args, _)] = apify_client_async_patcher.calls['run']['get'] + assert args[0].resource_id == 'parent-run' + + +async def test_failed_resurrection_keeps_the_record(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A resurrect request that fails raises from the call and leaves the record as it is, so a later call retries.""" + resurrect = Mock(side_effect=[RuntimeError('memory limit exceeded'), make_run('old-run', 'RUNNING')]) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTED')) + apify_client_async_patcher.patch('run', 'resurrect', replacement_method=resurrect) + record = stored_record( + 'old-run', 'ABORTED', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + with pytest.raises(RuntimeError, match='memory limit exceeded'): + await Actor.start('some-actor', run_name='scrape-eu') + stored_after_failure = await kvs.get_value(CHILD_RUNS_KEY) + run = await Actor.start('some-actor', run_name='scrape-eu') + + assert stored_after_failure == stored_registry({'scrape-eu': record}) + assert run.status == 'RUNNING' + + +async def test_resurrection_of_a_missing_run_starts_a_new_one( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """A run to resurrect that the API no longer knows is replaced by a new run.""" + not_found = NotFoundError(Mock(status_code=404, json=Mock(return_value={})), 1, method='POST') + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'ABORTED')) + apify_client_async_patcher.patch('run', 'resurrect', replacement_method=Mock(side_effect=not_found)) + record = stored_record( + 'old-run', 'ABORTED', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + run = await Actor.start('some-actor', run_name='scrape-eu') + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.id == 'new-run' + assert stored == stored_registry( + {'scrape-eu': stored_record('new-run', 'READY', abort_with_parent=True, resurrect_with_parent=True)} + ) + + +async def test_named_call_waits_for_the_resurrected_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A named call that resurrects its run waits for it and streams only its new log lines.""" + get_streamed_log = Mock(return_value=MagicMock()) + 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')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('old-run', 'SUCCEEDED')) + apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) + record = stored_record( + 'old-run', 'ABORTED', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + await seed_registry({'scrape-eu': record}) + run = await Actor.call('some-actor', run_name='scrape-eu') + + assert run.status == 'SUCCEEDED' + assert get_streamed_log.call_args.kwargs['from_start'] is False + + +@pytest.mark.parametrize( + 'method', + [ + pytest.param('start', id='start'), + pytest.param('call', id='call'), + pytest.param('start_task', id='start task'), + pytest.param('call_task', id='call task'), + ], +) +async def test_resurrect_with_parent_requires_tracked_run( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str +) -> None: + """With persistence off, `resurrect_with_parent` without a `run_name` raises before any run is started.""" + for resource in ('actor', 'task'): + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch(resource, 'call', return_value=make_run('new-run', 'SUCCEEDED')) + + async with Actor: + with pytest.raises(ValueError, match=r'`resurrect_with_parent` requires `run_name`'): + await getattr(Actor, method)('some-id', resurrect_with_parent=True) + + for resource in ('actor', 'task'): + assert apify_client_async_patcher.calls[resource]['start'] == [] + assert apify_client_async_patcher.calls[resource]['call'] == [] + + +@pytest.mark.usefixtures('persist_unnamed_child_runs') +@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'), + ], +) +async def test_new_run_records_resurrect_with_parent( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str +) -> None: + """Each method records `resurrect_with_parent` with the run it starts, also for a run without a name.""" + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + 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: + await getattr(Actor, method)('some-id', abort_with_parent=True, resurrect_with_parent=True, **kwargs) + [child_run] = Actor.child_runs.unnamed.values() + + assert child_run.record.abort_with_parent is True + assert child_run.record.resurrect_with_parent is True + assert child_run.record.aborted_with_parent is False + + +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() + client.run.return_value.abort = AsyncMock(return_value=make_run('old-run', 'ABORTING')) + + 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})) + registry = ChildRunRegistry(Actor.open_key_value_store) + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0.05) + assert not abort_task.done() + await registry.load() + await asyncio.wait_for(abort_task, timeout=1) + + client.run.return_value.abort.assert_awaited_once_with(gracefully=True) + + +@pytest.mark.parametrize( + 'stored', + [ + pytest.param([], id='empty list'), + pytest.param('', id='empty string'), + pytest.param(0, id='zero'), + ], +) +async def test_init_rejects_registry_of_another_json_type(stored: Any) -> None: + """Init raises a `ValueError` for a registry value that is not a JSON object, also when the value is falsy.""" + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored) + + with pytest.raises(ValueError, match=CHILD_RUNS_KEY): + await Actor.init() + + +async def test_failed_registry_write_does_not_stop_the_abort_of_child_runs( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The marked child runs are aborted also when the registry cannot be written during the abort.""" + client = Mock() + client.run.return_value.abort = AsyncMock(return_value=make_run('old-run', 'ABORTING')) + + async with Actor: + await seed_registry({'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + monkeypatch.setattr(registry, '_write', AsyncMock(side_effect=RuntimeError('KVS is down'))) + await registry.abort_runs_with_parent(client) + + client.run.return_value.abort.assert_awaited_once_with(gracefully=True) + assert 'Failed to record the child runs to abort with the parent' in caplog.text + assert 'Failed to record the child runs aborted with the parent' in caplog.text + + +async def test_start_that_outlasts_the_abort_is_not_flagged_as_aborted_with_parent( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A marked run whose start finishes after the abort gave up gets no abort request and no flag.""" + monkeypatch.setattr(_child_runs, '_ABORT_WITH_PARENT_TIMEOUT', timedelta(milliseconds=50)) + client = Mock() + client.run.return_value.abort = AsyncMock(return_value=make_run('new-run', 'ABORTING')) + started = asyncio.Event() + release = asyncio.Event() + + async def start_run() -> Run: + started.set() + await release.wait() + return make_run('new-run', 'READY') + + async with Actor: + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + key = ChildRunKey('named', 'scrape-eu') + start_task = asyncio.create_task( + registry.find_or_start(key, checksum='checksum', client=client, start_run=start_run, abort_with_parent=True) + ) + await started.wait() + await asyncio.wait_for(registry.abort_runs_with_parent(client), timeout=5) + release.set() + await start_task + record = registry.child_runs(client).named['scrape-eu'].record + + assert record.aborted_with_parent is False + client.run.return_value.abort.assert_not_awaited() + + +async def test_aborting_event_during_the_wait_for_an_aborting_run_stops_its_resurrection() -> None: + """A call that waits for a run to be aborted does not resurrect it once the parent gets `ABORTING`.""" + client = Mock() + waiting = asyncio.Event() + release = asyncio.Event() + + async def wait_for_finish(**_kwargs: Any) -> Run: + waiting.set() + await release.wait() + return make_run('old-run', 'ABORTED') + + client.run.return_value.get = AsyncMock(return_value=make_run('old-run', 'ABORTING')) + client.run.return_value.wait_for_finish = wait_for_finish + client.run.return_value.resurrect = AsyncMock(return_value=make_run('old-run', 'RUNNING')) + client.run.return_value.abort = AsyncMock(return_value=make_run('old-run', 'ABORTED')) + record = stored_record( + 'old-run', 'ABORTING', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + await seed_registry({'scrape-eu': record}) + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + call = asyncio.create_task( + registry.find_or_start( + ChildRunKey('named', 'scrape-eu'), checksum=record['checksum'], client=client, start_run=AsyncMock() + ) + ) + await waiting.wait() + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0) + release.set() + run, _ = await call + await abort_task + stored = registry.child_runs(client).named['scrape-eu'].record + + assert run.status == 'ABORTED' + client.run.return_value.resurrect.assert_not_awaited() + assert stored.aborted_with_parent is True + + +@pytest.mark.parametrize( + 'status', + [ + pytest.param('RUNNING', id='running'), + pytest.param('SUCCEEDED', id='succeeded'), + ], +) +async def test_child_run_seen_not_aborted_loses_the_flag_without_resurrect_with_parent( + apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +) -> None: + """A call without `resurrect_with_parent` clears `abortedWithParent` when it sees that the run is not aborted.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', status)) + record = stored_record('old-run', 'RUNNING', abort_with_parent=True, aborted_with_parent=True) + + async with Actor: + kvs = await seed_registry({'scrape-eu': record}) + await Actor.start('some-actor', run_name='scrape-eu') + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert stored['named']['scrape-eu']['abortedWithParent'] is False + + +async def test_failed_load_releases_an_abort_of_child_runs_that_waits_for_it() -> None: + """An abort of the child runs that waits for the registry returns when the load fails, and aborts nothing.""" + client = Mock() + client.run.return_value.abort = AsyncMock() + + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'scrape-eu': {'runId': 'old-run'}})) + registry = ChildRunRegistry(Actor.open_key_value_store) + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0) + with pytest.raises(ValueError, match=CHILD_RUNS_KEY): + await registry.load() + await asyncio.wait_for(abort_task, timeout=1) + + client.run.return_value.abort.assert_not_awaited() + + +async def test_abort_of_child_runs_stops_waiting_for_a_load_that_never_happens() -> None: + """An abort of the child runs that waits for the registry returns when the Actor gives up loading it.""" + client = Mock() + + async with Actor: + registry = ChildRunRegistry(Actor.open_key_value_store) + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0) + registry.stop_waiting_for_load() + await asyncio.wait_for(abort_task, timeout=1) + + client.run.assert_not_called() + + +async def test_aborting_event_during_the_parent_status_request_stops_the_resurrection() -> None: + """A parent that gets `ABORTING` while the registry asks for its status does not resurrect its child runs.""" + client = Mock() + client.run.return_value.get = AsyncMock(return_value=make_run('old-run', 'ABORTED')) + client.run.return_value.resurrect = AsyncMock(return_value=make_run('old-run', 'RUNNING')) + client.run.return_value.abort = AsyncMock(return_value=make_run('old-run', 'ABORTED')) + abort_tasks = list[asyncio.Task[None]]() + record = stored_record( + 'old-run', 'ABORTED', abort_with_parent=True, resurrect_with_parent=True, aborted_with_parent=True + ) + + async with Actor: + await seed_registry({'scrape-eu': record}) + + async def is_parent_aborting() -> bool: + # The answer was true before the event, which arrives while the request is in flight. + abort_tasks.append(asyncio.create_task(registry.abort_runs_with_parent(client))) + await asyncio.sleep(0) + return False + + registry = ChildRunRegistry(Actor.open_key_value_store, is_parent_aborting=is_parent_aborting) + await registry.load() + key = ChildRunKey('named', 'scrape-eu') + run, _ = await registry.find_or_start(key, checksum=record['checksum'], client=client, start_run=AsyncMock()) + await asyncio.gather(*abort_tasks) + with pytest.raises(RuntimeError, match='being aborted'): + await registry.find_or_start( + ChildRunKey('named', 'scrape-us'), + checksum='checksum', + client=client, + start_run=AsyncMock(), + abort_with_parent=True, + ) + + assert run.status == 'ABORTED' + client.run.return_value.resurrect.assert_not_awaited() + + +async def test_call_in_flight_during_aborting_keeps_the_flag_of_its_run() -> None: + """A call that fetches its run while the parent gets `ABORTING` does not erase `abortedWithParent`.""" + client = Mock() + fetching = asyncio.Event() + release_fetch = asyncio.Event() + release_abort = asyncio.Event() + + async def get_run(**_kwargs: Any) -> Run: + fetching.set() + await release_fetch.wait() + return make_run('old-run', 'RUNNING') + + async def abort_run(**_kwargs: Any) -> Run: + await release_abort.wait() + return make_run('old-run', 'ABORTING') + + client.run.return_value.get = get_run + client.run.return_value.abort = abort_run + record = stored_record('old-run', 'READY', abort_with_parent=True) + + async with Actor: + await seed_registry({'scrape-eu': record}) + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + key = ChildRunKey('named', 'scrape-eu') + call = asyncio.create_task( + registry.find_or_start(key, checksum=record['checksum'], client=client, start_run=AsyncMock()) + ) + await fetching.wait() + abort_task = asyncio.create_task(registry.abort_runs_with_parent(client)) + await asyncio.sleep(0.05) + release_fetch.set() + await call + flagged_after_call = registry.child_runs(client).named['scrape-eu'].record.aborted_with_parent + release_abort.set() + await abort_task + + assert flagged_after_call is True + + +async def test_failed_abort_request_clears_the_flag_of_its_run() -> None: + """A run whose abort request fails is not recorded as aborted with the parent.""" + client = Mock() + client.run.return_value.abort = AsyncMock(side_effect=RuntimeError('abort failed')) + + async with Actor: + await seed_registry({'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + await registry.abort_runs_with_parent(client) + record = registry.child_runs(client).named['scrape-eu'].record + + assert record.aborted_with_parent is False + + +async def test_slow_registry_write_does_not_stop_the_abort_of_child_runs( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The marked child runs are aborted also when the write of their flags does not finish in time.""" + monkeypatch.setattr(_child_runs, '_ABORT_RECORD_TIMEOUT', timedelta(milliseconds=20)) + client = Mock() + client.run.return_value.abort = AsyncMock(return_value=make_run('old-run', 'ABORTING')) + never = asyncio.Event() + + async with Actor: + await seed_registry({'scrape-eu': stored_record('old-run', 'RUNNING', abort_with_parent=True)}) + registry = ChildRunRegistry(Actor.open_key_value_store) + await registry.load() + monkeypatch.setattr(registry, '_write', never.wait) + await asyncio.wait_for(registry.abort_runs_with_parent(client), timeout=5) + + client.run.return_value.abort.assert_awaited_once_with(gracefully=True) + assert 'Recording the child runs to abort with the parent did not finish' in caplog.text diff --git a/tests/unit/actor/test_actor_env_helpers.py b/tests/unit/actor/test_actor_env_helpers.py index 61cf24ee..623e3b65 100644 --- a/tests/unit/actor/test_actor_env_helpers.py +++ b/tests/unit/actor/test_actor_env_helpers.py @@ -35,6 +35,7 @@ ApifyEnvVars.HEADLESS, ApifyEnvVars.IS_AT_HOME, ApifyEnvVars.PERSIST_STORAGE, + ApifyEnvVars.PERSIST_UNNAMED_CHILD_RUNS, ApifyEnvVars.PURGE_ON_START, ApifyEnvVars.USER_IS_PAYING, ]