Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- **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": {"<kind>:<value>": 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.
- **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": {"<kind>:<value>": record}}`, kinds `run`, `name` and `implicit`), 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.
Expand Down
23 changes: 18 additions & 5 deletions src/apify/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
KeyValueStoreChildRunTracker,
checksum_request,
checksum_run_options,
implicit_key,
name_key,
)
from apify._configuration import Configuration
Expand Down Expand Up @@ -258,6 +259,12 @@ async def __aenter__(self) -> Self:
self.log.info('Initializing Actor', extra=get_system_info())
self.log.debug('Configuration initialized')

if self.configuration.auto_memoize_child_runs and not self._child_run_registry.is_enabled:
raise ValueError(
'`Configuration.auto_memoize_child_runs` needs child run tracking, which is turned off with '
'`child_run_tracker=None`.'
)

# Update the global Actor proxy to refer to this instance.
cast('Proxy', Actor).__wrapped__ = self # ty: ignore[invalid-assignment]
self._is_exiting = False
Expand Down Expand Up @@ -479,8 +486,9 @@ def child_runs(self) -> list[ChildRun]:

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:<run ID>`, or `name:<run name>` for a run started with
a `run_name`), the stored `record`, and a `client` for the run:
the `key` of the run in the child run registry (`run:<run ID>`, `name:<run name>` for a run started with
a `run_name`, or `implicit:<checksum>` for a run with an implicit run name from
`Configuration.auto_memoize_child_runs`), the stored `record`, and a `client` for the run:

```python
for key, record, client in Actor.child_runs:
Expand Down Expand Up @@ -1471,7 +1479,10 @@ async def _start_child_run(
options: dict[str, Any],
abort_with_parent: bool,
) -> tuple[Run, str | None, bool]:
"""Start a child run and record it, or return the run recorded under `run_name`.
"""Start a child run and record it, or return the run recorded under its explicit or implicit run name.

With `Configuration.auto_memoize_child_runs`, a call without a `run_name` uses the checksum of its request as
an implicit run name.

Returns:
The run, its key in the child run registry (`None` with child run tracking off), and whether it was newly
Expand All @@ -1480,7 +1491,8 @@ async def _start_child_run(
if not self._child_run_registry.is_enabled:
return await start_run(), None, True

if run_name is None:
is_implicit = run_name is None and self.configuration.auto_memoize_child_runs
if run_name is None and not is_implicit:
run = await start_run()
key = await self._child_run_registry.record(run, client=client)
return run, key, True
Expand All @@ -1492,8 +1504,9 @@ async def _start_child_run(
content_type=content_type,
options=options,
run_name=run_name,
require_json_input=is_implicit,
)
key = name_key(run_name)
key = implicit_key(checksum) if run_name is None else name_key(run_name)
run, is_new = await self._child_run_registry.find_or_start(
key,
checksum=checksum,
Expand Down
16 changes: 16 additions & 0 deletions src/apify/_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ def name_key(run_name: str) -> str:
return f'name:{run_name}'


def implicit_key(checksum: str) -> str:
"""Return the registry key of a child run whose implicit run name is the checksum of its request."""
return f'implicit:{checksum}'


@docs_group('Actor')
class ChildRunRecord(BaseModel):
"""A child run as recorded in the child run registry of this Actor run.
Expand Down Expand Up @@ -258,6 +263,7 @@ def checksum_request(
content_type: str | None = None,
options: dict[str, Any] | None = None,
run_name: str | None = None,
require_json_input: bool = False,
) -> str:
"""Hash the Actor or task, the input, and the run options of a start, in the same JSON shape as the JS SDK.

Expand All @@ -270,13 +276,23 @@ def checksum_request(
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.
require_json_input: Whether an input that is not JSON raises instead. An implicit run name needs the input,
since without it calls with different inputs would get the same name.

Raises:
TypeError: If `require_json_input` is set and the client would not send the input as JSON.
"""
request: dict[str, Any] = (
{'type': 'actor', 'id': actor_id} if actor_id is not None else {'type': 'task', 'id': task_id}
)
try:
json_input = _to_json_input(run_input, content_type)
except TypeError as exc:
if require_json_input:
raise TypeError(
f'An implicit run name needs a JSON input, but {exc}. Pass a `run_name`, or turn '
'`Configuration.auto_memoize_child_runs` off.'
) from exc
logger.warning(
'The input of child run "%s" is not JSON (%s), so it was not checked against the recorded run',
run_name,
Expand Down
13 changes: 13 additions & 0 deletions src/apify/_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,19 @@ class Configuration(CrawleeConfiguration):
),
] = 'https://api.apify.com'

auto_memoize_child_runs: Annotated[
bool,
Field(
validation_alias='apify_auto_memoize_child_runs',
description=(
'Whether a run that `Actor.start`, `Actor.call`, `Actor.start_task` or `Actor.call_task` starts '
'without a `run_name` gets an implicit run name derived from the Actor or task, the input and the run '
'options. An identical call then returns the recorded run, also after a migration, and its input must '
'be JSON. It requires child run tracking'
),
),
] = False

dedicated_cpus: Annotated[
float | None,
Field(
Expand Down
1 change: 1 addition & 0 deletions src/apify/_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ class ApifyEnvVars(StrEnum):
ACTOR_PRICING_INFO = 'APIFY_ACTOR_PRICING_INFO'
API_BASE_URL = 'APIFY_API_BASE_URL'
API_PUBLIC_BASE_URL = 'APIFY_API_PUBLIC_BASE_URL'
AUTO_MEMOIZE_CHILD_RUNS = 'APIFY_AUTO_MEMOIZE_CHILD_RUNS'
CHARGED_ACTOR_EVENT_COUNTS = 'APIFY_CHARGED_ACTOR_EVENT_COUNTS'
DEDICATED_CPUS = 'APIFY_DEDICATED_CPUS'
DEFAULT_BROWSER_PATH = 'APIFY_DEFAULT_BROWSER_PATH'
Expand Down
86 changes: 86 additions & 0 deletions tests/unit/actor/test_actor_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1690,3 +1690,89 @@ async def test_registry_keeps_unknown_kinds_fields_and_members(
},
'version': 2,
}


async def test_implicit_run_name_returns_run_of_identical_call(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch
) -> None:
"""With `auto_memoize_child_runs`, an identical call without a name returns the run recorded for the first one."""
monkeypatch.setenv('APIFY_AUTO_MEMOIZE_CHILD_RUNS', 'true')
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('new-run', 'RUNNING'))

async with Actor:
first = await Actor.start('some-actor', {'q': 1}, build='beta')
second = await Actor.start('some-actor', {'q': 1}, build='beta', memory_mbytes=2048)
keys = [child_run.key for child_run in Actor.child_runs]

checksum = checksum_request(actor_id='some-actor', run_input={'q': 1}, options={'build': 'beta'})
assert first.id == second.id == 'new-run'
assert len(apify_client_async_patcher.calls['actor']['start']) == 1
assert keys == [f'implicit:{checksum}']


@pytest.mark.parametrize(
'second_call',
[
pytest.param({'run_input': {'q': 2}}, id='different input'),
pytest.param({'run_input': {'q': 1}, 'build': 'beta'}, id='different build'),
pytest.param({'run_input': {'q': 1}, 'run_name': 'second'}, id='explicit run name'),
],
)
async def test_implicit_run_name_starts_new_run_for_different_call(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch, second_call: dict[str, Any]
) -> None:
"""With `auto_memoize_child_runs`, a call with another request or with an explicit run name starts a new run."""
monkeypatch.setenv('APIFY_AUTO_MEMOIZE_CHILD_RUNS', 'true')
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:
first = await Actor.start('some-actor', {'q': 1})
second = await Actor.start('some-actor', **second_call)

assert (first.id, second.id) == ('first-run', 'second-run')


async def test_implicit_run_name_rejects_input_not_sent_as_json(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch
) -> None:
"""With `auto_memoize_child_runs`, a call without a name and with an input that is not JSON raises a `TypeError`."""
monkeypatch.setenv('APIFY_AUTO_MEMOIZE_CHILD_RUNS', 'true')
apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY'))

async with Actor:
with pytest.raises(TypeError, match='implicit run name needs a JSON input'):
await Actor.start('some-actor', 'plain text')

assert apify_client_async_patcher.calls['actor']['start'] == []


async def test_implicit_run_name_resolves_run_recorded_by_earlier_process(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A run recorded under an implicit run name by an earlier process is returned by an identical call."""
monkeypatch.setenv('APIFY_AUTO_MEMOIZE_CHILD_RUNS', 'true')
checksum = checksum_request(actor_id='some-actor', run_input={'q': 1})
record = {'runId': 'old-run', 'status': 'RUNNING', 'abortWithParent': False, 'checksum': checksum}
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', 'SUCCEEDED'))

async with Actor:
kvs = await Actor.open_key_value_store()
await kvs.set_value(CHILD_RUNS_KEY, stored_registry(runs={f'implicit:{checksum}': record}))

async with Actor:
run = await Actor.start('some-actor', {'q': 1})

assert run.id == 'old-run'
assert run.status == 'SUCCEEDED'
assert apify_client_async_patcher.calls['actor']['start'] == []


async def test_auto_memoize_without_tracking_fails_init(monkeypatch: pytest.MonkeyPatch) -> None:
"""Turning `auto_memoize_child_runs` on with child run tracking off makes the Actor start fail."""
monkeypatch.setenv('APIFY_AUTO_MEMOIZE_CHILD_RUNS', 'true')

with pytest.raises(ValueError, match='auto_memoize_child_runs'):
await Actor(child_run_tracker=None).init()
1 change: 1 addition & 0 deletions tests/unit/actor/test_actor_env_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
]

BOOL_ENV_VARS: list[ApifyEnvVars] = [
ApifyEnvVars.AUTO_MEMOIZE_CHILD_RUNS,
ApifyEnvVars.DISABLE_BROWSER_SANDBOX,
ApifyEnvVars.HEADLESS,
ApifyEnvVars.IS_AT_HOME,
Expand Down