From 48e6d35c185271247be33b209baaa1e9fdf1ee1d Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:05:18 +0100 Subject: [PATCH 1/3] feat: track every child run in a registry --- .rules.md | 2 +- src/apify/__init__.py | 4 + src/apify/_actor.py | 448 ++++++------ src/apify/_child_runs.py | 578 ++++++++++----- tests/e2e/test_actor_child_runs.py | 21 +- tests/unit/actor/test_actor_child_runs.py | 855 ++++++++++++++++------ tests/unit/actor/test_actor_helpers.py | 43 +- 7 files changed, 1297 insertions(+), 654 deletions(-) diff --git a/.rules.md b/.rules.md index 268863c1f..738c6f9b5 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`) — every run started by `Actor.start`, `call`, `start_task` and `call_task` is recorded in the child run registry (`{"runs": {":": record}}`, kinds `run` and `name`), kept by a `ChildRunTracker` (by default 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`. `Actor(child_run_tracker=None)` turns tracking off. The registry format is shared with the JS SDK. - **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 76e7a382d..4a8d0e69b 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, ChildRunTracker 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', + 'ChildRunTracker', 'Configuration', 'Event', 'EventAbortingData', diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 143157491..47bb16093 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -37,7 +37,14 @@ ChargingManagerImplementation, charge_lock_if_charging, ) -from apify._child_runs import ChildRunRegistry +from apify._child_runs import ( + TERMINAL_RUN_STATUSES, + ChildRunRegistry, + KeyValueStoreChildRunTracker, + checksum_request, + checksum_run_options, + name_key, +) from apify._configuration import Configuration from apify._consts import ( EVENT_LISTENERS_TIMEOUT, @@ -69,6 +76,7 @@ from crawlee._types import JsonSerializable from crawlee.proxy_configuration import _NewUrlFunction + from apify._child_runs import ChildRun, ChildRunTracker from apify._webhook import Webhook MainReturnType = TypeVar('MainReturnType') @@ -78,8 +86,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.', + 'Child run features (`run_name`, `abort_with_parent`, `Actor.child_runs` and `child_run_tracker`) 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, @@ -150,6 +158,8 @@ def __init__( status_message: str | None = None, event_listeners_timeout: timedelta | None = EVENT_LISTENERS_TIMEOUT, cleanup_timeout: timedelta = timedelta(seconds=30), + child_run_tracker: ChildRunTracker | Literal['default'] | None = 'default', + disable_excessive_child_run_warning: bool = False, ) -> None: """Initialize a new instance. @@ -162,6 +172,13 @@ def __init__( status_message: Final status message to display upon Actor termination. event_listeners_timeout: Maximum time to wait for Actor event listeners to complete before exiting. cleanup_timeout: Maximum time to wait for cleanup tasks to finish. + child_run_tracker: Storage of the child run registry, which records every run started by `Actor.start`, + `Actor.call`, `Actor.start_task` and `Actor.call_task`. `default` keeps it in the default key-value + store, and a custom `ChildRunTracker` can keep it elsewhere. `None` turns child run tracking off, with + `Actor.child_runs`, `run_name` and `abort_with_parent`. Child run tracking is experimental, so its + behavior and interface may change in future versions. + disable_excessive_child_run_warning: Whether to mute the warning logged once the child run registry holds + many records. """ self._configuration = configuration self._configure_logging = configure_logging @@ -181,7 +198,13 @@ 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) + if child_run_tracker == 'default': + child_run_tracker = KeyValueStoreChildRunTracker(self.open_key_value_store) + elif child_run_tracker is not None: + _warn_child_runs_experimental() + self._child_run_registry = ChildRunRegistry( + child_run_tracker, warn_on_excessive_runs=not disable_excessive_child_run_warning + ) self._runs_with_redirected_log: set[str | None] = set() """IDs of the runs whose log a call of this Actor redirects right now.""" @@ -209,7 +232,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, unless child run tracking is off. - On the Apify platform, forwards the status messages of Crawlee crawlers to the run status message. - Configures logging after all core services are registered. @@ -256,6 +279,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. @@ -398,6 +423,8 @@ def __call__( event_listeners_timeout: timedelta | None = EVENT_LISTENERS_TIMEOUT, status_message: str | None = None, cleanup_timeout: timedelta = timedelta(seconds=30), + child_run_tracker: ChildRunTracker | Literal['default'] | None = 'default', + disable_excessive_child_run_warning: bool = False, ) -> Self: """Make a new Actor instance with a non-default configuration. @@ -411,6 +438,8 @@ def __call__( event_listeners_timeout=event_listeners_timeout, status_message=status_message, cleanup_timeout=cleanup_timeout, + child_run_tracker=child_run_tracker, + disable_excessive_child_run_warning=disable_excessive_child_run_warning, ) @property @@ -445,25 +474,33 @@ 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) -> list[ChildRun]: + """The child runs of this Actor run, in the order in which they were started. - 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: + Every run started by `Actor.start`, `Actor.call`, `Actor.start_task` or `Actor.call_task` is listed, also one + started by an earlier process of this Actor run, before a migration, reboot or resurrection. Each entry holds + the `key` of the run in the child run registry (`run:`, or `name:` for a run started with + a `run_name`), the stored `record`, and a `client` for the run: ```python - run = await Actor.child_runs['my-child'].wait_for_finish() + for key, record, client in Actor.child_runs: + 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. + + Raises: + RuntimeError: If child run tracking is turned off with `child_run_tracker=None`. 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) + if not self._child_run_registry.is_enabled: + raise RuntimeError('`Actor.child_runs` is not available, since child run tracking is turned off.') + return self._child_run_registry.child_runs(self.apify_client) @cached_property def configuration(self) -> Configuration: @@ -1143,24 +1180,24 @@ async def start( webhooks: Optional ad-hoc webhooks (https://docs.apify.com/webhooks/ad-hoc-webhooks) associated with 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. + run_name: Optional name of the child run, unique within this Actor run. Every child run is recorded in the + child run registry, and a later call with the same name returns the run recorded under it, 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, `build`, `force_permission_level` + or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is + logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so + their behavior and interface may change in future versions. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. + It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the + one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises + a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run + leaves the child running. 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.') + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) if run_name is not None: _warn_child_runs_experimental() @@ -1171,35 +1208,30 @@ async def start( client = self.new_client(token=token) if token else self.apify_client actor_client = client.actor(actor_id) - start_run = partial( - actor_client.start, - run_input=run_input, - content_type=content_type, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), - force_permission_level=force_permission_level, - webhooks=to_client_representations(webhooks), - ) - - if run_name is None: - return await start_run() - - run, _ = await self._find_or_start_child_run( - run_name, + run, _, _ = await self._start_child_run( + run_name=run_name, + client=client, + start_run=partial( + actor_client.start, + run_input=run_input, + content_type=content_type, + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + run_timeout=self._resolve_run_timeout(timeout), + force_permission_level=force_permission_level, + webhooks=to_client_representations(webhooks), + ), actor_id=actor_id, run_input=run_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, + content_type=content_type, + options=checksum_run_options( + build=build, + force_permission_level=force_permission_level, + webhooks=to_client_representations(webhooks), + ), abort_with_parent=abort_with_parent, ) return run @@ -1348,24 +1380,24 @@ async def call( logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined 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. + run_name: Optional name of the child run, unique within this Actor run. Every child run is recorded in the + child run registry, and a later call with the same name returns the run recorded under it, 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, `build`, `force_permission_level` + or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is + logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so + their behavior and interface may change in future versions. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. + It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the + one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises + a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run + leaves the child running. 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.') + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) if run_name is not None: _warn_child_runs_experimental() @@ -1376,9 +1408,11 @@ async def call( client = self.new_client(token=token) if token else self.apify_client actor_client = client.actor(actor_id) - - if run_name is None: - run = await actor_client.call( + started_run, key, is_new = await self._start_child_run( + run_name=run_name, + client=client, + start_run=partial( + actor_client.start, run_input=run_input, content_type=content_type, build=build, @@ -1389,87 +1423,92 @@ async def call( run_timeout=self._resolve_run_timeout(timeout), force_permission_level=force_permission_level, webhooks=to_client_representations(webhooks), - wait_duration=wait, - logger=logger, - ) - else: - started_run, is_new = await self._find_or_start_child_run( - run_name, - actor_id=actor_id, - run_input=run_input, - client=client, - start_run=partial( - actor_client.start, - run_input=run_input, - content_type=content_type, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), - force_permission_level=force_permission_level, - webhooks=to_client_representations(webhooks), - ), + ), + actor_id=actor_id, + run_input=run_input, + content_type=content_type, + 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, - abort_with_parent=abort_with_parent, - ) - # The earlier attempt of this call already streamed the log of a reattached or resurrected 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 - ) + force_permission_level=force_permission_level, + webhooks=to_client_representations(webhooks), + ), + abort_with_parent=abort_with_parent, + ) + # 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( + key, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new + ) if run is None: raise RuntimeError(f'Failed to call Actor with ID "{actor_id}".') return run - async def _find_or_start_child_run( + def _check_child_run_options(self, *, run_name: str | None, abort_with_parent: bool) -> None: + """Validate the child run options of `start`, `call`, `start_task` and `call_task`. + + Raises: + ValueError: If an option needs child run tracking and it is off, or `abort_with_parent` lacks `run_name`. + """ + if not self._child_run_registry.is_enabled and (run_name is not None or abort_with_parent): + raise ValueError( + '`run_name` and `abort_with_parent` need child run tracking, which is turned off with ' + '`child_run_tracker=None`.' + ) + if abort_with_parent and run_name is None: + raise ValueError('`abort_with_parent` requires `run_name`.') + + async def _start_child_run( self, - name: str, *, - actor_id: str | None = None, - task_id: str | None = None, - run_input: Any, + run_name: str | None, 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, + actor_id: str | None = None, + task_id: str | None = None, + run_input: Any = None, + content_type: str | None = None, + options: dict[str, Any], abort_with_parent: bool, - ) -> tuple[Run, bool]: - return await self._child_run_registry.find_or_start( - name, + ) -> tuple[Run, str | None, bool]: + """Start a child run and record it, or return the run recorded under `run_name`. + + Returns: + The run, its key in the child run registry (`None` with child run tracking off), and whether it was newly + started. + """ + if not self._child_run_registry.is_enabled: + return await start_run(), None, True + + if run_name is None: + run = await start_run() + key = await self._child_run_registry.record(run, client=client) + return run, key, True + + checksum = checksum_request( actor_id=actor_id, task_id=task_id, run_input=run_input, + content_type=content_type, + options=options, + run_name=run_name, + ) + key = name_key(run_name) + 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, ) + return run, key, is_new 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: str | None, run_client: RunClientAsync, run: Run, *, @@ -1477,13 +1516,13 @@ 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 finished_run = await self._wait_for_run(run_client, wait=wait, logger=logger, from_start=from_start) - if finished_run is not None: - await self._child_run_registry.update(name, finished_run) + if key is not None and finished_run is not None: + await self._child_run_registry.update(key, finished_run) return finished_run async def _wait_for_run( @@ -1566,24 +1605,24 @@ async def start_task( webhooks: Optional webhooks (https://docs.apify.com/webhooks) associated with 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, 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. + run_name: Optional name of the child run, unique within this Actor run. Every child run is recorded in the + child run registry, and a later call with the same name returns the run recorded under it, 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, `build`, `force_permission_level` + or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is + logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so + their behavior and interface may change in future versions. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. + It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the + one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises + a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run + leaves the child running. 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.') + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) if run_name is not None: _warn_child_runs_experimental() @@ -1592,34 +1631,25 @@ async def start_task( _warn_max_items_deprecated() client = self.new_client(token=token) if token else self.apify_client - task_client = client.task(task_id) - start_run = partial( - task_client.start, - task_input=task_input, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), - webhooks=to_client_representations(webhooks), - ) - if run_name is None: - return await start_run() - - run, _ = await self._find_or_start_child_run( - run_name, + task_client = client.task(task_id) + run, _, _ = await self._start_child_run( + run_name=run_name, + client=client, + start_run=partial( + task_client.start, + task_input=task_input, + build=build, + max_items=max_items, + max_total_charge_usd=max_total_charge_usd, + restart_on_error=restart_on_error, + memory_mbytes=memory_mbytes, + run_timeout=self._resolve_run_timeout(timeout), + webhooks=to_client_representations(webhooks), + ), 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, webhooks=to_client_representations(webhooks)), abort_with_parent=abort_with_parent, ) return run @@ -1676,24 +1706,24 @@ async def call_task( will redirect logs to the provided logger. With a logger, the method returns about 6 seconds after the run finishes or `wait` runs out, since the redirect waits that long for the last status message of the run. - 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. + run_name: Optional name of the child run, unique within this Actor run. Every child run is recorded in the + child run registry, and a later call with the same name returns the run recorded under it, 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, `build`, `force_permission_level` + or `webhooks` raises a `ValueError`. An input that is not sent as JSON is not checked, and a warning is + logged. It raises a `ValueError` with child run tracking off. Named child runs are experimental, so + their behavior and interface may change in future versions. + abort_with_parent: If true, the child run is gracefully aborted when this Actor run is gracefully aborted. + It requires `run_name` and child run tracking, and the value is recorded under the name, replacing the + one from an earlier call. Once this Actor run is being gracefully aborted, a call with it raises + a `RuntimeError` and starts or returns no run. A hard abort, a timeout or a crash of this Actor run + leaves the child running. 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.') + self._check_child_run_options(run_name=run_name, abort_with_parent=abort_with_parent) if run_name is not None: _warn_child_runs_experimental() @@ -1704,10 +1734,11 @@ async def call_task( client = self.new_client(token=token) if token else self.apify_client task_client = client.task(task_id) - - if run_name is None: - # The client's `call` cannot redirect the log of the run, so the run is started and waited for here. - started_run = await task_client.start( + started_run, key, is_new = await self._start_child_run( + run_name=run_name, + client=client, + start_run=partial( + task_client.start, task_input=task_input, build=build, max_items=max_items, @@ -1718,37 +1749,16 @@ async def call_task( webhooks=to_client_representations(webhooks), # A request that times out is retried, and a retried start request can start a second run. timeout='no_timeout', - ) - run = await self._wait_for_run(client.run(started_run.id), wait=wait, logger=logger, from_start=True) - else: - started_run, is_new = await self._find_or_start_child_run( - run_name, - task_id=task_id, - run_input=task_input, - client=client, - start_run=partial( - task_client.start, - task_input=task_input, - build=build, - max_items=max_items, - max_total_charge_usd=max_total_charge_usd, - restart_on_error=restart_on_error, - memory_mbytes=memory_mbytes, - 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, - abort_with_parent=abort_with_parent, - ) - # The earlier attempt of this call already streamed the log of a reattached or resurrected 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 - ) + ), + task_id=task_id, + run_input=task_input, + options=checksum_run_options(build=build, webhooks=to_client_representations(webhooks)), + abort_with_parent=abort_with_parent, + ) + # 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( + key, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new + ) if run is None: raise RuntimeError(f'Failed to call Task with ID "{task_id}".') diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index 4b3bc52de..4f2b81a04 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -3,86 +3,298 @@ import asyncio import hashlib import json -from datetime import datetime +from abc import ABC, abstractmethod from logging import getLogger -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, 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 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.""" - -_RESURRECTABLE_STATUSES = frozenset({'ABORTED', 'TIMED-OUT'}) - _ABORTED_STATUSES = frozenset({'ABORTING', 'ABORTED'}) +TERMINAL_RUN_STATUSES = frozenset({'SUCCEEDED', 'FAILED', 'ABORTED', 'TIMED-OUT'}) +"""Statuses of a run that is finished. A run in any other status is active.""" + _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.""" _NOT_FOUND_RETRY_INTERVAL_SECS = 0.25 +EXCESSIVE_CHILD_RUNS_THRESHOLD = 50 +"""Number of records above which the registry logs a warning about its size, once per process.""" + + +def run_key(run_id: str) -> str: + """Return the registry key of a child run started without a run name.""" + return f'run:{run_id}' -class ChildRunSnapshot(BaseModel): - """A child run as last observed by this Actor run.""" - model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel) +def name_key(run_name: str) -> str: + """Return the registry key of a child run started with `run_name`.""" + return f'name:{run_name}' + + +@docs_group('Actor') +class ChildRunRecord(BaseModel): + """A child run as recorded in the child run registry of this Actor run. + + Fields this SDK version does not know, e.g. written by a newer SDK before a metamorph, are kept. + """ + + model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel, frozen=True, extra='allow') run_id: str """ID of the run.""" 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.""" + abort_with_parent: bool = False + """Whether the run is aborted when this Actor run is gracefully aborted.""" + checksum: str | None = None + """SHA-256 of the request a named run was started with. `None` for a run started without a run name.""" -class ChildRunRecord(ChildRunSnapshot): - """The current run tracked under a name in the child run registry, with the runs it replaced.""" - checksum: str - """Hash of the Actor or task and the input the current run was started with.""" +@docs_group('Actor') +class ChildRun(NamedTuple): + """A child run of this Actor run, as listed in `Actor.child_runs`.""" - 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.""" + key: str + """Key of the run in the child run registry, such as `run:` or `name:`.""" - abort_with_parent: bool = False - """Whether the current run is aborted when this Actor run is gracefully aborted.""" + record: ChildRunRecord + """Read-only copy of the record stored in the child run registry.""" + + client: RunClientAsync + """Client for the run.""" + + +@docs_group('Actor') +class ChildRunTracker(ABC): + """Storage of the child run registry of an Actor run. + + The Actor reads the records once, when it starts, and stores a record every time it changes. The default tracker + keeps the registry in the default key-value store under the `APIFY_ACTOR_CHILD_RUNS` key. A custom tracker, passed + as `Actor(child_run_tracker=...)`, can store the records elsewhere or encrypt them. + """ + + @abstractmethod + async def list_runs(self) -> dict[str, ChildRunRecord]: + """Return the stored records by their key, in the order in which they were first stored. + + Raises: + ValueError: If the stored registry is malformed. + """ + + @abstractmethod + async def store_run(self, key: str, record: ChildRunRecord) -> None: + """Store `record` under `key`, replacing the record stored under it. + + Args: + key: Key of the record, such as `run:` or `name:`. + record: The record to store. + """ + + +class _StoredRegistry(BaseModel): + """The child run registry as stored in the default key-value store. + + Top-level members this SDK version does not know are kept. + """ + + model_config = ConfigDict(extra='allow') + + runs: dict[str, ChildRunRecord] = Field(default_factory=dict) + + +class KeyValueStoreChildRunTracker(ChildRunTracker): + """Child run tracker that keeps the registry in the default key-value store of the Actor run.""" + + def __init__(self, open_key_value_store: Callable[[], Awaitable[KeyValueStore]]) -> None: + self._open_key_value_store = open_key_value_store + self._stored = _StoredRegistry() + + async def list_runs(self) -> dict[str, ChildRunRecord]: + key_value_store = await self._open_key_value_store() + stored = await key_value_store.get_value(CHILD_RUNS_KEY) + try: + self._stored = _StoredRegistry.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 + return dict(self._stored.runs) + + async def store_run(self, key: str, record: ChildRunRecord) -> None: + self._stored.runs[key] = record + key_value_store = await self._open_key_value_store() + await key_value_store.set_value( + CHILD_RUNS_KEY, self._stored.model_dump(mode='json', by_alias=True, exclude_none=True) + ) + + +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('.') -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.""" + # 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.lower(): + raise TypeError(f'the content type of the input is {content_type!r}') + if isinstance(run_input, (str, bytes, bytearray)) or StreamedRequestBody.is_streamable(run_input): + raise TypeError(f'the input is a {type(run_input).__name__}') + 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, + force_permission_level: ActorPermissionLevel | None = None, + webhooks: list[WebhookRepresentation] | None = None, +) -> dict[str, Any]: + """Return the run options that enter the checksum and are set, under the names and with the values of the API. + + Only the options that change which code runs, or what it is allowed to do, enter the checksum. The others, such + as the memory limit or the timeout, can differ between processes of this Actor run. + + Args: + build: The Actor build to run. + force_permission_level: Permission level of the run. + webhooks: Ad-hoc webhooks of the run. + """ + 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, + '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, + run_name: str | 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. + + An input that the client would not send as JSON is left out, and a warning says that it was not checked. + + 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`. + run_name: Run name of the call, used in the warning about an input that is not 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() + try: + json_input = _to_json_input(run_input, content_type) + except TypeError as exc: + logger.warning( + 'The input of child run "%s" is not JSON (%s), so it was not checked against the recorded run', + run_name, + exc, + ) + json_input = None + 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,153 +306,158 @@ 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. + """Records every child run of this Actor run, so that a migration, reboot, or resurrection of it keeps them. - 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. + Every change is stored by the tracker 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: - self._open_key_value_store = open_key_value_store + def __init__(self, tracker: ChildRunTracker | None, *, warn_on_excessive_runs: bool = True) -> None: + """Initialize a new instance. + + Args: + tracker: Storage of the records, or `None` to turn child run tracking off. + warn_on_excessive_runs: Whether to log a warning once the registry holds too many records. + """ + self._tracker = tracker + self._warn_on_excessive_runs = warn_on_excessive_runs self._records: dict[str, ChildRunRecord] | None = None + self._loaded = asyncio.Event() + """Set once the Actor has read the records from the tracker, 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.""" + """Guards loading the records and storing them through the tracker.""" + self._key_locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary() + """Serializes `find_or_start` per key. A lock is dropped once no call under its key holds it.""" self._clients: dict[str, ApifyClientAsync] = {} - """Client the run under each name was last started or looked up with. Lost on a migration.""" + """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._warned_excessive_runs = False + + @property + def is_enabled(self) -> bool: + """Whether child run tracking is on.""" + return self._tracker is not None async def find_or_start( self, - name: str, + key: str, *, - 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, ) -> 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. 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`. + recorded under `key`. 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. + ValueError: If the run recorded under `key` was started with a different request. RuntimeError: If `abort_with_parent` is set and this Actor run is being gracefully aborted. No run is - started, resurrected or reattached. + started or returned. """ - checksum = checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input) - - async with self._name_locks.setdefault(name, asyncio.Lock()): + async with self._key_locks.setdefault(key, 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}" 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 + record = self._get_records().get(key) + + if record is not None: + if record.checksum != checksum: + raise ValueError( + f'The run name of child run "{key}" was already used for a different Actor, task, input or ' + 'run options. Use a unique `run_name` for each child run.' + ) + + run = await _get_recorded_run(client.run(record.run_id)) + + if run is not None: + logger.info('Reattaching to child run "%s"', key, extra={'run_id': run.id, 'status': run.status}) + updated_record = record.model_copy( + update={'status': run.status, 'abort_with_parent': abort_with_parent} + ) + if updated_record != record: + await self._store(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, + extra={'run_id': record.run_id}, ) - 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 - - 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.' - ) + run = await start_run() + new_record = ChildRunRecord( + run_id=run.id, + status=run.status, + abort_with_parent=abort_with_parent, + checksum=checksum, + ) + await self._store(key, new_record) + self._clients[key] = client + return run, True - if record.abort_with_parent != abort_with_parent: - await self._save(name, record.model_copy(update={'abort_with_parent': abort_with_parent})) + async def record(self, run: Run, *, client: ApifyClientAsync) -> str: + """Record a run started without a run name. - 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}) + Args: + run: The run as returned by the start request. + client: Client the run was started with. - await self.update(name, run) - self._clients[name] = client - return run, False + Returns: + Key of the run in the registry. + """ + key = run_key(run.id) + await self._store(key, ChildRunRecord(run_id=run.id, status=run.status)) + self._clients[key] = client + return key - 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) -> list[ChildRun]: + """Return the key, the record and a client of every recorded run, in recording order. - 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: list[ChildRun] = [] + for key, record in self._get_records().items(): + client = self._clients.get(key, default_client) + child_runs.append(ChildRun(key=key, record=record, client=client.run(record.run_id))) + return child_runs - 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: str, 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._get_records().get(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._store(key, record.model_copy(update={'status': run.status})) async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: """Gracefully abort every recorded run marked `abort_with_parent`, and refuse to start any more of them. @@ -250,72 +467,73 @@ async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: the start records it. 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})) + # 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._records is None: + return + # Keys with a start in flight are not recorded yet, so their locks are awaited too. + await asyncio.gather(*(self._abort(key, client) for key in {*self._records, *self._key_locks})) - async def _abort(self, name: str, default_client: ApifyClientAsync) -> None: - async with self._name_locks.setdefault(name, asyncio.Lock()): - record = (await self._load()).get(name) + async def _abort(self, key: str, default_client: ApifyClientAsync) -> None: + async with self._key_locks.setdefault(key, asyncio.Lock()): + record = self._get_records().get(key) if record is None or not record.abort_with_parent: return - run_client = self._clients.get(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, extra={'run_id': record.run_id}) 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, extra={'run_id': record.run_id}) else: 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, 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 - - async def load(self) -> dict[str, ChildRunRecord]: - """Read the records from the default key-value store, replacing any read before.""" + async def load(self) -> None: + """Read the records through the tracker, replacing any read before. Does nothing with tracking off.""" 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() + if self._tracker is not None: + self._records = await self._tracker.list_runs() + self._warn_if_excessive() + 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 _get_records(self) -> dict[str, ChildRunRecord]: + if self._records is None: + raise RuntimeError('The child run registry is not loaded.') + return self._records + + async def _store(self, key: str, record: ChildRunRecord) -> None: + records = self._get_records() + if self._tracker is None: + raise RuntimeError('Child run tracking is turned off.') 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') - ) + records[key] = record + self._warn_if_excessive() + await self._tracker.store_run(key, record) + + def _warn_if_excessive(self) -> None: + if ( + not self._warn_on_excessive_runs + or self._warned_excessive_runs + or len(self._get_records()) <= EXCESSIVE_CHILD_RUNS_THRESHOLD + ): + return + self._warned_excessive_runs = True + logger.warning( + 'Too many child runs (%d). Tracking them can cause performance issues and excessive key-value store ' + 'usage. Turn child run tracking off with `Actor(child_run_tracker=None)`, or mute this warning with ' + '`Actor(disable_excessive_child_run_warning=True)`.', + len(self._get_records()), + ) diff --git a/tests/e2e/test_actor_child_runs.py b/tests/e2e/test_actor_child_runs.py index 05b1352af..a01dcb0f9 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_run.key for child_run in child_runs] == ['name:child'], f'child_runs={child_runs}' + assert child_runs[0].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']['runs']['name: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)) diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index ffe876497..6c75900fc 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1,21 +1,36 @@ 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, 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, + ChildRun, + ChildRunRecord, + ChildRunRegistry, + ChildRunTracker, + KeyValueStoreChildRunTracker, + checksum_request, + checksum_run_options, + name_key, +) +from apify._webhook import to_client_representations from apify.events import ApifyEventManager if TYPE_CHECKING: @@ -25,7 +40,7 @@ from apify.storages import KeyValueStore -pytestmark = pytest.mark.filterwarnings('ignore:Named child runs:UserWarning') +pytestmark = pytest.mark.filterwarnings('ignore:Child run features:UserWarning') def make_run(run_id: str, status: str) -> Run: @@ -58,17 +73,30 @@ def stored_record( 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, ) -> dict[str, Any]: - """Build a registry record as it is stored in the default KVS.""" + """Build the registry record of a named run as it is stored in the default KVS.""" return { 'runId': run_id, 'status': status, - 'startedAt': STARTED_AT, - 'checksum': checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input), - 'history': history or [], 'abortWithParent': abort_with_parent, + 'checksum': checksum_request(actor_id=actor_id, task_id=task_id, run_input=run_input, options=options), + } + + +def stored_registry( + named: dict[str, dict[str, Any]] | None = None, runs: dict[str, dict[str, Any]] | None = None +) -> dict[str, Any]: + """Build the registry value as it is stored in the default KVS, from named records and records by their key.""" + named_runs = {name_key(name): record for name, record in (named or {}).items()} + return {'runs': {**named_runs, **(runs or {})}} + + +def named_child_runs(child_runs: list[ChildRun]) -> dict[str, ChildRun]: + """Return the entries of `Actor.child_runs` started with a run name, by that name.""" + return { + child_run.key.removeprefix('name:'): child_run for child_run in child_runs if child_run.key.startswith('name:') } @@ -87,11 +115,12 @@ 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', 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 +134,106 @@ 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')} - - -async def test_unnamed_start_is_not_recorded(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: - """A start without a name leaves the registry untouched.""" - apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - - async with 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 stored == stored_registry({'scrape-eu': stored_record('new-run', 'READY')}) @pytest.mark.parametrize( - 'status', + ('method', 'resource'), [ - pytest.param('READY', id='ready'), - pytest.param('RUNNING', id='running'), - pytest.param('SUCCEEDED', id='succeeded'), + 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_named_start_reuses_recorded_run( - apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +async def test_unnamed_run_is_recorded_under_its_run_id( + 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)) + """A run started without a name is recorded under `run:`, and a call records its final status.""" + 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')) async with Actor: - await record_child_run('scrape-eu', 'old-run') - run = await Actor.start('some-actor', run_name='scrape-eu') + kwargs = {'logger': None} if method.startswith('call') else {} + await getattr(Actor, method)('some-id', **kwargs) + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) - assert run.id == 'old-run' - assert run.status == status - assert apify_client_async_patcher.calls['actor']['start'] == [] + status = 'SUCCEEDED' if method.startswith('call') else 'READY' + assert stored == {'runs': {'run:new-run': {'runId': 'new-run', 'status': status, 'abortWithParent': False}}} -@pytest.mark.parametrize( - 'status', - [ - pytest.param('ABORTED', id='aborted'), - pytest.param('TIMED-OUT', id='timed out'), - ], -) -async def test_named_start_resurrects_recorded_run( - apify_client_async_patcher: ApifyClientAsyncPatcher, status: str +async def test_unnamed_runs_with_the_same_request_are_separate( + apify_client_async_patcher: ApifyClientAsyncPatcher, ) -> None: - """A recorded run that was aborted or timed out is resurrected, and its options are passed through.""" - 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')) + """Two starts without a name start two runs, both listed in `Actor.child_runs` in the order they were started.""" + runs = iter([make_run('first-run', 'READY'), make_run('second-run', 'READY')]) + apify_client_async_patcher.patch('actor', 'start', replacement_method=lambda *_args, **_kwargs: next(runs)) 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', {'q': 1}) + await Actor.start('some-actor', {'q': 1}) + keys = [child_run.key for child_run in Actor.child_runs] - 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 + assert keys == ['run:first-run', 'run:second-run'] @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 named_child_runs(child_runs)['scrape-eu'].client.resource_id == 'new-run' + [warning] = [record for record in caplog.records if record.levelname == 'WARNING'] + assert 'Child run "name: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 +245,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 +260,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 +348,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['runs']['name: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['runs']['name: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 +442,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 +451,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 == [] + + 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 +474,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'] == [] @@ -498,21 +556,20 @@ async def wait_for_finish(*_args: Any, **_kwargs: Any) -> Run: assert get_streamed_log.call_count == 1 -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, logger=None) + run = await Actor.call_task('some-task', run_name='scrape-eu', logger=None) 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( @@ -524,7 +581,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', logger=None) assert apify_client_async_patcher.calls['task']['start'] == [] @@ -546,22 +603,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: @@ -574,7 +625,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'] == [] @@ -592,12 +645,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( @@ -622,6 +675,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'), ], ) @@ -629,52 +683,73 @@ 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({}, {'build': 'beta'}, id='option added'), + pytest.param({'build': 'latest'}, {'build': 'beta'}, id='option changed'), + pytest.param({'forcePermissionLevel': 'FULL_PERMISSIONS'}, {}, 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 checked run options returns the recorded run, whatever its other run options.""" + apify_client_async_patcher.patch('run', 'get', return_value=make_run('old-run', 'SUCCEEDED')) + recorded_options = { + 'build': 'beta', + 'forcePermissionLevel': 'LIMITED_PERMISSIONS', + '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.""" @@ -716,6 +791,136 @@ def test_checksum_matches_js_sdk(request_kwargs: dict[str, Any], expected: str) assert checksum_request(**request_kwargs) == expected +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"}' + ) + + assert checksum == hashlib.sha256(canonical.encode()).hexdigest() + + +@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"}}' + + assert ( + checksum_request(actor_id='some-actor', run_input=run_input) == hashlib.sha256(canonical.encode()).hexdigest() + ) + + +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_leaves_out_input_not_sent_as_json( + run_input: Any, content_type: str | None, caplog: pytest.LogCaptureFixture +) -> None: + """An input that the client does not serialize to JSON is left out of the checksum, with a warning.""" + checksum = checksum_request( + actor_id='some-actor', run_input=run_input, content_type=content_type, run_name='scrape-eu' + ) + + assert checksum == checksum_request(actor_id='some-actor') + assert 'The input of child run "scrape-eu" is not JSON' in caplog.text + + +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', + 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', + 'webhooks': [{'eventTypes': ['ACTOR.RUN.FAILED'], 'requestUrl': 'https://example.com/hook'}], + } + assert checksum_run_options() == {} + + +async def test_named_start_returns_recorded_run_for_input_not_sent_as_json( + apify_client_async_patcher: ApifyClientAsyncPatcher, caplog: pytest.LogCaptureFixture +) -> None: + """A named start with an input that is not sent as JSON returns the recorded run without checking the input.""" + 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')) + + async with Actor: + await record_child_run('scrape-eu', 'old-run') + run = await Actor.start('some-actor', 'plain text', run_name='scrape-eu') + + assert run.id == 'old-run' + assert apify_client_async_patcher.calls['actor']['start'] == [] + assert 'was not checked against the recorded run' in caplog.text + + 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')) @@ -726,7 +931,7 @@ async def test_reattached_run_status_is_recorded(apify_client_async_patcher: Api kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored == {'scrape-eu': stored_record('old-run', 'SUCCEEDED')} + 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: @@ -739,16 +944,13 @@ async def test_named_call_records_finished_status(apify_client_async_patcher: Ap 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: - """`Actor.child_runs` is empty when no run was started with a `run_name`.""" - apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) - +async def test_child_runs_is_empty_without_child_runs() -> None: + """`Actor.child_runs` is empty when no child run was started.""" async with Actor: - await Actor.start('some-actor') - assert Actor.child_runs == {} + assert Actor.child_runs == [] def test_child_runs_requires_initialized_actor() -> None: @@ -758,38 +960,63 @@ 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', actor_id=None, task_id='some-task'), + }, + runs={'run:other-run': {'runId': 'other-run', 'status': 'SUCCEEDED', 'abortWithParent': False}}, + ), ) 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 named_child_runs(child_runs).items()} == { 'scrape-eu': 'eu-run', 'scrape-us': 'us-run', } + assert named_child_runs(child_runs)['scrape-us'].record.status == 'FAILED' + assert [child_run.key for child_run in child_runs] == ['name:scrape-eu', 'name:scrape-us', 'run:other-run'] -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 named_child_runs(child_runs).keys() == {'scrape-eu'} + key, record, client = named_child_runs(child_runs)['scrape-eu'] + assert key == 'name:scrape-eu' + assert client.resource_id == 'new-run' + assert record == ChildRunRecord( + run_id='new-run', + 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 = named_child_runs(Actor.child_runs)['scrape-eu'].record + with pytest.raises(ValidationError, match='frozen'): + record.status = 'SUCCEEDED' # ty: ignore[invalid-assignment] + assert named_child_runs(Actor.child_runs)['scrape-eu'].record.status == 'READY' async def test_child_runs_uses_client_of_named_start( @@ -815,8 +1042,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 named_child_runs(child_runs)['custom'].client._http_client is custom_http_client + assert named_child_runs(child_runs)['recorded'].client._http_client is default_http_client async def test_child_runs_keeps_client_of_name_after_rejected_reuse( @@ -828,12 +1055,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 named_child_runs(child_runs)['scrape-eu'].client._http_client is default_http_client async def test_child_runs_keeps_client_of_name_after_failed_lookup( @@ -850,7 +1077,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 named_child_runs(child_runs)['scrape-eu'].client._http_client is default_http_client @pytest.mark.parametrize( @@ -888,7 +1115,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['runs']['name:scrape-eu']['abortWithParent'] is True async def test_named_call_task_records_abort_with_parent( @@ -903,7 +1130,7 @@ 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['runs']['name:scrape-eu']['abortWithParent'] is True async def test_reattach_replaces_recorded_abort_with_parent( @@ -918,8 +1145,8 @@ async def test_reattach_replaces_recorded_abort_with_parent( kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) - assert stored['scrape-eu']['runId'] == 'old-run' - assert stored['scrape-eu']['abortWithParent'] is True + assert stored['runs']['name:scrape-eu']['runId'] == 'old-run' + assert stored['runs']['name:scrape-eu']['abortWithParent'] is True async def test_aborting_event_aborts_marked_child_runs( @@ -943,18 +1170,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', 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() @@ -963,8 +1188,8 @@ async def abort_run(run_client: Any, *_args: Any, **_kwargs: Any) -> Run: assert sorted(args[0].resource_id for args, _ in aborts) == ['finished-run', 'ready-run', 'running-run'] assert all(kwargs == {'gracefully': True} for _, kwargs in aborts) assert apify_client_async_patcher.calls['run']['get'] == [] - assert 'Aborted child run "running" with the parent' in caplog.text - assert 'Aborted child run "ready" with the parent' in caplog.text + assert 'Aborted child run "name:running" with the parent' in caplog.text + assert 'Aborted child run "name:ready" with the parent' in caplog.text assert 'Aborted child run "finished"' not in caplog.text @@ -979,7 +1204,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', 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() @@ -1004,18 +1230,18 @@ 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', 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() aborts = apify_client_async_patcher.calls['run']['abort'] assert sorted(args[0].resource_id for args, _ in aborts) == ['broken-run', 'healthy-run'] - assert 'Failed to abort child run "broken"' in caplog.text - assert 'Aborted child run "healthy" with the parent' in caplog.text + assert 'Failed to abort child run "name:broken"' in caplog.text + assert 'Aborted child run "name:healthy" with the parent' in caplog.text async def test_child_run_is_aborted_with_the_client_it_was_started_with() -> None: @@ -1025,14 +1251,13 @@ async def test_child_run_is_aborted_with_the_client_it_was_started_with() -> Non child_client.run.return_value.abort = AsyncMock(return_value=make_run('new-run', 'ABORTING')) async with Actor: - registry = ChildRunRegistry(Actor.open_key_value_store) + registry = ChildRunRegistry(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + await registry.load() await registry.find_or_start( - 'scrape-eu', - actor_id='some-actor', - run_input=None, + name_key('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) @@ -1051,16 +1276,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)}) - registry = ChildRunRegistry(Actor.open_key_value_store) - with pytest.raises(ValueError, match='already used for a different Actor, task or input'): + record = stored_record('old-run', 'RUNNING', abort_with_parent=True) + await kvs.set_value(CHILD_RUNS_KEY, stored_registry({'scrape-eu': record})) + registry = ChildRunRegistry(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + 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, + name_key('scrape-eu'), + checksum='other-checksum', client=other_client, start_run=AsyncMock(), - resurrect_run=AsyncMock(), ) await registry.abort_runs_with_parent(default_client) @@ -1081,15 +1306,14 @@ async def start_run() -> Run: return make_run('new-run', 'READY') async with Actor: - registry = ChildRunRegistry(Actor.open_key_value_store) + registry = ChildRunRegistry(KeyValueStoreChildRunTracker(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, + name_key('scrape-eu'), + checksum='checksum', client=client, start_run=start_run, - resurrect_run=AsyncMock(), abort_with_parent=True, ) ) @@ -1118,17 +1342,13 @@ async def start_run() -> Run: queued_start_run = AsyncMock() 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)) + registry = ChildRunRegistry(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + await registry.load() + key = name_key('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) @@ -1181,7 +1401,8 @@ async def test_named_call_once_aborting_does_not_resurrect_the_aborted_child( 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() @@ -1283,3 +1504,187 @@ async def test_child_runs_warns_experimental() -> None: _ = Actor.child_runs assert [warning.filename for warning in warnings] == [__file__] + + +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(KeyValueStoreChildRunTracker(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_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(KeyValueStoreChildRunTracker(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(KeyValueStoreChildRunTracker(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_tracking_off_starts_runs_without_recording_them( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """With `child_run_tracker=None`, a start neither reads nor writes the registry.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor(child_run_tracker=None): + run = await Actor.start('some-actor') + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert run.id == 'new-run' + assert stored is None + + +@pytest.mark.parametrize( + 'kwargs', + [ + pytest.param({'run_name': 'scrape-eu'}, id='run name'), + pytest.param({'run_name': 'scrape-eu', 'abort_with_parent': True}, id='abort with parent'), + ], +) +async def test_tracking_off_rejects_child_run_options( + apify_client_async_patcher: ApifyClientAsyncPatcher, kwargs: dict[str, Any] +) -> None: + """With child run tracking off, `run_name` and `abort_with_parent` raise a `ValueError` and start no run.""" + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor(child_run_tracker=None): + with pytest.raises(ValueError, match='child run tracking'): + await Actor.start('some-actor', **kwargs) + + assert apify_client_async_patcher.calls['actor']['start'] == [] + + +async def test_tracking_off_child_runs_raises() -> None: + """With child run tracking off, `Actor.child_runs` raises a `RuntimeError`.""" + async with Actor(child_run_tracker=None): + with pytest.raises(RuntimeError, match='child run tracking is turned off'): + _ = Actor.child_runs + + +async def test_custom_tracker_stores_and_lists_records(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """A custom tracker gets every record to store, and its listed records are the ones `Actor.child_runs` shows.""" + recorded = ChildRunRecord(run_id='old-run', status='SUCCEEDED') + tracker = AsyncMock(spec=ChildRunTracker) + tracker.list_runs.return_value = {'run:old-run': recorded} + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor(child_run_tracker=tracker): + await Actor.start('some-actor') + keys = [child_run.key for child_run in Actor.child_runs] + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert keys == ['run:old-run', 'run:new-run'] + tracker.store_run.assert_awaited_once_with('run:new-run', ChildRunRecord(run_id='new-run', status='READY')) + assert stored is None + + +@pytest.mark.parametrize( + ('disable_warning', 'expected_warnings'), + [ + pytest.param(False, 1, id='warning on'), + pytest.param(True, 0, id='warning muted'), + ], +) +async def test_excessive_child_runs_warning( + apify_client_async_patcher: ApifyClientAsyncPatcher, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + *, + disable_warning: bool, + expected_warnings: int, +) -> None: + """Once the registry holds more records than the threshold, one warning is logged, unless it is muted.""" + monkeypatch.setattr(_child_runs, 'EXCESSIVE_CHILD_RUNS_THRESHOLD', 2) + runs = iter([make_run(f'run-{index}', 'READY') for index in range(4)]) + apify_client_async_patcher.patch('actor', 'start', replacement_method=lambda *_args, **_kwargs: next(runs)) + + async with Actor(disable_excessive_child_run_warning=disable_warning): + for _ in range(4): + await Actor.start('some-actor') + + assert caplog.text.count('Too many child runs (3)') == expected_warnings + assert 'Too many child runs (4)' not in caplog.text + + +async def test_registry_keeps_unknown_kinds_fields_and_members( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """Records of unknown kinds, unknown record fields and unknown top-level members survive a rewrite.""" + unknown_record = {'runId': 'other-run', 'status': 'RUNNING', 'abortWithParent': False, 'extra': 1} + apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY')) + + async with Actor: + kvs = await Actor.open_key_value_store() + await kvs.set_value(CHILD_RUNS_KEY, {'runs': {'future:x': unknown_record}, 'version': 2}) + + async with Actor: + keys = [child_run.key for child_run in Actor.child_runs] + await Actor.start('some-actor') + kvs = await Actor.open_key_value_store() + stored = await kvs.get_value(CHILD_RUNS_KEY) + + assert keys == ['future:x'] + assert stored == { + 'runs': { + 'future:x': unknown_record, + 'run:new-run': {'runId': 'new-run', 'status': 'READY', 'abortWithParent': False}, + }, + 'version': 2, + } diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index a6d6460de..29b0b3cee 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -127,16 +127,19 @@ async def test_new_client_uses_configured_api_public_base_url(monkeypatch: pytes await my_actor.exit() -async def test_call_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: - apify_client_async_patcher.patch('actor', 'call', return_value=fake_actor_run) +async def test_call_actor( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + apify_client_async_patcher.patch('actor', 'start', return_value=fake_actor_run) actor_id = 'some-actor-id' async with Actor: - await Actor.call(actor_id) + run = await Actor.call(actor_id) - assert len(apify_client_async_patcher.calls['actor']['call']) == 1 - # The first argument is ActorClientAsync, which was called, let's check its id. - assert apify_client_async_patcher.calls['actor']['call'][0][0][0].resource_id == actor_id + assert run is run_waiting.finished_run + [(start_args, _)] = apify_client_async_patcher.calls['actor']['start'] + assert start_args[0].resource_id == actor_id + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 async def test_call_actor_task( @@ -250,7 +253,7 @@ async def test_start_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, ('client_resource', 'client_method', 'sdk_method'), [ pytest.param('actor', 'start', 'start', id='start'), - pytest.param('actor', 'call', 'call', id='call'), + pytest.param('actor', 'start', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), pytest.param('task', 'start', 'call_task', id='call_task'), ], @@ -276,7 +279,7 @@ async def test_max_items_forwarded_to_client( ('client_resource', 'client_method', 'sdk_method'), [ pytest.param('actor', 'start', 'start', id='start'), - pytest.param('actor', 'call', 'call', id='call'), + pytest.param('actor', 'start', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), @@ -304,7 +307,7 @@ async def test_max_items_warns_deprecated( ('client_resource', 'client_method', 'sdk_method'), [ pytest.param('actor', 'start', 'start', id='start'), - pytest.param('actor', 'call', 'call', id='call'), + pytest.param('actor', 'start', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), @@ -330,7 +333,7 @@ async def test_no_max_items_warning_without_max_items( ('client_resource', 'client_method', 'sdk_method'), [ pytest.param('actor', 'start', 'start', id='start'), - pytest.param('actor', 'call', 'call', id='call'), + pytest.param('actor', 'start', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), pytest.param('task', 'start', 'call_task', id='call_task'), ], @@ -589,7 +592,7 @@ async def listener(_data: object) -> None: _ACTOR_REMOTE_METHODS = [ pytest.param('actor', 'start', 'start', 'some-actor-id', id='start'), - pytest.param('actor', 'call', 'call', 'some-actor-id', id='call'), + pytest.param('actor', 'start', 'call', 'some-actor-id', id='call'), pytest.param('task', 'start', 'start_task', 'some-task-id', id='start_task'), pytest.param('task', 'start', 'call_task', 'some-task-id', id='call_task'), ] @@ -712,20 +715,23 @@ async def test_get_remaining_time_returns_positive_when_timeout_in_future() -> N @pytest.mark.parametrize('method_name', ['start', 'call']) +@pytest.mark.usefixtures('run_waiting') async def test_actor_start_and_call_skipped_when_no_inherited_time_remains( apify_client_async_patcher: ApifyClientAsyncPatcher, + fake_actor_run: Run, method_name: str, ) -> None: """Test that Actor.start/Actor.call with `timeout='inherit'` is skipped when the run is past its timeout.""" - apify_client_async_patcher.patch('actor', method_name, return_value=Mock()) + apify_client_async_patcher.patch('actor', 'start', return_value=fake_actor_run) - async with Actor: + # Child run tracking would write to the platform storage once the Actor pretends to be at home. + async with Actor(child_run_tracker=None): Actor.configuration.is_at_home = True Actor.configuration.timeout_at = datetime.now(tz=UTC) - timedelta(minutes=5) await getattr(Actor, method_name)('some-actor-id', timeout='inherit') - assert len(apify_client_async_patcher.calls['actor'][method_name]) == 1 - assert apify_client_async_patcher.calls['actor'][method_name][0][1]['run_timeout'] == timedelta(seconds=1) + assert len(apify_client_async_patcher.calls['actor']['start']) == 1 + assert apify_client_async_patcher.calls['actor']['start'][0][1]['run_timeout'] == timedelta(seconds=1) @pytest.mark.parametrize( @@ -735,15 +741,18 @@ async def test_actor_start_and_call_skipped_when_no_inherited_time_remains( pytest.param('start', 'call_task', id='call_task'), ], ) +@pytest.mark.usefixtures('run_waiting') async def test_actor_task_methods_skipped_when_no_inherited_time_remains( apify_client_async_patcher: ApifyClientAsyncPatcher, + fake_actor_run: Run, client_method: str, actor_method_name: str, ) -> None: """Test that start_task/call_task with `timeout='inherit'` is skipped when the run is past its timeout.""" - apify_client_async_patcher.patch('task', client_method, return_value=Mock()) + apify_client_async_patcher.patch('task', client_method, return_value=fake_actor_run) - async with Actor: + # Child run tracking would write to the platform storage once the Actor pretends to be at home. + async with Actor(child_run_tracker=None): Actor.configuration.is_at_home = True Actor.configuration.timeout_at = datetime.now(tz=UTC) - timedelta(minutes=5) await getattr(Actor, actor_method_name)('some-task-id', timeout='inherit') From d26710a74428b38d9d130f002095094c45e4db8b Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:28:48 +0100 Subject: [PATCH 2/3] test: mock the run wait in the helper tests that cover `Actor.call` --- tests/unit/actor/test_actor_helpers.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 29b0b3cee..8faa2f7ed 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -258,6 +258,7 @@ async def test_start_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, pytest.param('task', 'start', 'call_task', id='call_task'), ], ) +@pytest.mark.usefixtures('run_waiting') async def test_max_items_forwarded_to_client( apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, @@ -285,6 +286,7 @@ async def test_max_items_forwarded_to_client( pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) +@pytest.mark.usefixtures('run_waiting') async def test_max_items_warns_deprecated( apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, @@ -313,6 +315,7 @@ async def test_max_items_warns_deprecated( pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) +@pytest.mark.usefixtures('run_waiting') async def test_no_max_items_warning_without_max_items( apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, @@ -338,6 +341,7 @@ async def test_no_max_items_warning_without_max_items( pytest.param('task', 'start', 'call_task', id='call_task'), ], ) +@pytest.mark.usefixtures('run_waiting') async def test_max_total_charge_usd_forwarded_to_client( apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, @@ -599,6 +603,7 @@ async def listener(_data: object) -> None: @pytest.mark.parametrize(('client_resource', 'client_method', 'actor_method_name', 'entity_id'), _ACTOR_REMOTE_METHODS) +@pytest.mark.usefixtures('run_waiting') async def test_remote_method_with_webhooks( *, apify_client_async_patcher: ApifyClientAsyncPatcher, @@ -626,6 +631,7 @@ async def test_remote_method_with_webhooks( @pytest.mark.parametrize(('client_resource', 'client_method', 'actor_method_name', 'entity_id'), _ACTOR_REMOTE_METHODS) +@pytest.mark.usefixtures('run_waiting') async def test_remote_method_with_timedelta_timeout( *, apify_client_async_patcher: ApifyClientAsyncPatcher, From e3a89824ecc3cf2299d18dd53c6efa1219078930 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:36:27 +0100 Subject: [PATCH 3/3] test: ignore unrelated warnings in the warning assertions --- tests/unit/actor/test_actor_child_runs.py | 6 ++++-- tests/unit/actor/test_actor_helpers.py | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 6c75900fc..b28269623 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1484,7 +1484,8 @@ async def test_named_run_warns_experimental( with pytest.warns(UserWarning, match='experimental') as warnings: await method(target, run_name='scrape-eu', **kwargs) - assert [warning.filename for warning in warnings] == [__file__] + # Only the user warnings count: a `ResourceWarning` from an object of an earlier test can be collected here. + assert [warning.filename for warning in warnings if issubclass(warning.category, UserWarning)] == [__file__] async def test_unnamed_start_does_not_warn_experimental(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: @@ -1503,7 +1504,8 @@ async def test_child_runs_warns_experimental() -> None: with pytest.warns(UserWarning, match='experimental') as warnings: _ = Actor.child_runs - assert [warning.filename for warning in warnings] == [__file__] + # Only the user warnings count: a `ResourceWarning` from an object of an earlier test can be collected here. + assert [warning.filename for warning in warnings if issubclass(warning.category, UserWarning)] == [__file__] async def test_aborting_event_before_the_registry_is_loaded_waits_for_it() -> None: diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 8faa2f7ed..309110629 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -301,8 +301,8 @@ async def test_max_items_warns_deprecated( with pytest.warns(FutureWarning, match='`max_total_charge_usd`') as record: await getattr(Actor, sdk_method)('some-id', max_items=42) - assert len(record) == 1 - assert record[0].filename == __file__ + # Only the future warnings count: a `ResourceWarning` from an object of an earlier test can be collected here. + assert [warning.filename for warning in record if issubclass(warning.category, FutureWarning)] == [__file__] @pytest.mark.parametrize(