Skip to content
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.
- **Named child runs** (`_child_runs.py`) — runs started with `run_name` are persisted in the default key-value store so they can be reattached after a migration or resurrection; exposed through `Actor.child_runs`.
- **Child runs** (`_child_runs.py`) — runs started with `run_name`, and with `Configuration.persist_unnamed_child_runs` also the ones without it, are recorded in the default key-value store under `APIFY_ACTOR_CHILD_RUNS`, so a later process of the parent (after a migration, reboot, or resurrection) gets them back; exposed through `Actor.child_runs`.
- **Storage clients** (`storage_clients/`) implement Crawlee's storage client interface: `ApifyStorageClient` talks to the Apify API (separate sub-clients for single vs. shared request queues), `FileSystemStorageClient` adds Apify-specific key-value store behavior, and `SmartApifyStorageClient` delegates to the cloud client on the platform and to the local one elsewhere.
- **Events** — `ApifyEventManager` receives platform events over a WebSocket.
- **Errors** — `apify.errors` only re-exports the exceptions from `apify_client.errors`; the SDK defines no error classes of its own, and API calls raise the client exceptions unchanged.
Expand Down
4 changes: 4 additions & 0 deletions src/apify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
)

from apify._actor import Actor
from apify._child_runs import ChildRun, ChildRunRecord, ChildRuns
from apify._configuration import Configuration
from apify._consts import ActorEnvVars, ApifyEnvVars
from apify._proxy_configuration import ProxyConfiguration, ProxyInfo
Expand All @@ -26,6 +27,9 @@
'ActorEnvVars',
'ActorEventTypes',
'ApifyEnvVars',
'ChildRun',
'ChildRunRecord',
'ChildRuns',
'Configuration',
'Event',
'EventAbortingData',
Expand Down
373 changes: 243 additions & 130 deletions src/apify/_actor.py

Large diffs are not rendered by default.

713 changes: 535 additions & 178 deletions src/apify/_child_runs.py

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions src/apify/_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,18 @@ class Configuration(CrawleeConfiguration):
),
] = timedelta(minutes=5)

persist_unnamed_child_runs: Annotated[
bool,
Field(
validation_alias='apify_persist_unnamed_child_runs',
description=(
'Whether the runs that `Actor.start`, `Actor.call`, `Actor.start_task`, and `Actor.call_task` start '
'without a `run_name` are recorded in the default key-value store and reused by an identical call. '
'Such a call then needs a JSON input, and the store suits at most a few thousand recorded runs'
),
),
] = False

proxy_hostname: Annotated[
str,
Field(
Expand Down
1 change: 1 addition & 0 deletions src/apify/_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class ApifyEnvVars(StrEnum):
METAMORPH_AFTER_SLEEP_MILLIS = 'APIFY_METAMORPH_AFTER_SLEEP_MILLIS'
PERSIST_STATE_INTERVAL_MILLIS = 'APIFY_PERSIST_STATE_INTERVAL_MILLIS'
PERSIST_STORAGE = 'APIFY_PERSIST_STORAGE'
PERSIST_UNNAMED_CHILD_RUNS = 'APIFY_PERSIST_UNNAMED_CHILD_RUNS'
PROXY_HOSTNAME = 'APIFY_PROXY_HOSTNAME'
PROXY_PASSWORD = 'APIFY_PROXY_PASSWORD'
PROXY_PORT = 'APIFY_PROXY_PORT'
Expand Down
86 changes: 74 additions & 12 deletions tests/e2e/test_actor_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ async def main() -> None:
return

child_runs = Actor.child_runs
assert child_runs.keys() == {'child'}, f'child_runs={child_runs}'
assert child_runs['child'].resource_id == child_run_id, f'child_runs={child_runs}'
assert child_runs.named.keys() == {'child'}, f'child_runs={child_runs}'
assert child_runs.named['child'].client.resource_id == child_run_id, f'child_runs={child_runs}'

run = await Actor.call(actor_id=actor_id, run_input={'is_child': True}, run_name='child')
assert run is not None, 'run is None'
Expand All @@ -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:
Expand All @@ -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


Expand Down Expand Up @@ -123,11 +120,76 @@ async def main() -> None:
else:
raise AssertionError('The parent run did not record the child run in time.')

child_run_id = record['value']['child']['runId']
child_run_id = record['value']['named']['child']['runId']
parent_run_client = apify_client_async.run(parent_run.id)
await parent_run_client.abort(gracefully=True)
await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=120))

child_run = await apify_client_async.run(child_run_id).wait_for_finish(wait_duration=timedelta(seconds=120))
assert child_run is not None
assert child_run.status == 'ABORTED'


async def test_named_child_run_is_resurrected_with_parent(
make_actor: MakeActorFunction,
apify_client_async: ApifyClientAsync,
) -> None:
"""A child run aborted with the parent is resurrected by the same call after the parent is resurrected."""

async def main() -> None:
async with Actor:
actor_input = (await Actor.get_input()) or {}
if actor_input.get('is_child') is True:
await asyncio.sleep(300)
return

actor_id = Actor.configuration.actor_id or ''
is_resurrected = 'child' in Actor.child_runs.named
run = await Actor.start(
actor_id=actor_id,
run_input={'is_child': True},
run_name='child',
abort_with_parent=True,
resurrect_with_parent=True,
)

if not is_resurrected:
await asyncio.sleep(300)
return

assert run.status in {'READY', 'RUNNING'}, f'run.status={run.status}'
await Actor.apify_client.run(run.id).abort()

actor = await make_actor(label='child-run-resurrect-parent', main_func=main)
parent_run = await actor.start()
parent_kvs = apify_client_async.key_value_store(parent_run.default_key_value_store_id)

# Wait for the parent to record the child run.
for _ in range(60):
if record := await parent_kvs.get_record(CHILD_RUNS_KEY):
break
await asyncio.sleep(2)
else:
raise AssertionError('The parent run did not record the child run in time.')

child_run_id = record['value']['named']['child']['runId']
child_run_client = apify_client_async.run(child_run_id)
parent_run_client = apify_client_async.run(parent_run.id)
await parent_run_client.abort(gracefully=True)
await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=120))
aborted_child_run = await child_run_client.wait_for_finish(wait_duration=timedelta(seconds=120))
assert aborted_child_run is not None
assert aborted_child_run.status == 'ABORTED'

await parent_run_client.resurrect()
resurrected_parent_run = await parent_run_client.wait_for_finish(wait_duration=timedelta(seconds=300))
assert resurrected_parent_run is not None
assert resurrected_parent_run.status == 'SUCCEEDED'

record = await parent_kvs.get_record(CHILD_RUNS_KEY)
assert record is not None
assert record['value']['named']['child']['runId'] == child_run_id
assert record['value']['named']['child']['abortedWithParent'] is False
child_run = await child_run_client.get()
assert child_run is not None
assert child_run.stats.resurrect_count == 1
Loading
Loading