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
43 changes: 34 additions & 9 deletions src/apify/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ async def __aexit__(
case the Actor:

- Stops forwarding crawler status messages to the run status message.
- Rejects new child run starts, and waits up to 10 s for the ones already sent to be recorded.
- With a non-zero exit code, aborts the child runs started with `abort_with_parent`, waiting up to 10 s.
- Emits the `EXIT` event.
- Cancels periodic `PERSIST_STATE` events.
Expand Down Expand Up @@ -369,6 +370,10 @@ async def __aexit__(
self.event_manager.off(event=Event.CRAWLER_STATUS, listener=self._forward_crawler_status)

async def finalize() -> None:
# A later process of this Actor run, e.g. after a resurrection, gets every started run back.
self._child_run_registry.close()
await self._child_run_registry.wait_for_starts_in_flight()

if self.exit_code != 0 and self._child_run_registry.is_enabled:
await self._abort_child_runs()

Expand Down Expand Up @@ -1817,7 +1822,9 @@ async def metamorph(

The platform stops the current Actor container and starts a new container with the new Actor instead. All
the default storages are preserved, and the new input is stored under the `INPUT-METAMORPH-1` key in the same
default key-value store.
default key-value store. The target Actor also gets the child runs this Actor run recorded. Before the
metamorph, this method waits up to 10 seconds for the child run starts that are already sent, and it holds
back the ones that are not sent yet.

Args:
target_actor_id: ID of the target Actor that the run should be transformed into
Expand All @@ -1839,13 +1846,22 @@ async def metamorph(
if not self.configuration.actor_run_id:
raise RuntimeError('actor_run_id cannot be None when running on the Apify platform.')

self.log.debug('Metamorphing the Actor run into target Actor %r.', target_actor_id)
await self.apify_client.run(self.configuration.actor_run_id).metamorph(
target_actor_id=target_actor_id,
run_input=run_input,
target_actor_build=target_actor_build,
content_type=content_type,
)
# The target Actor inherits the child run registry, so every run started here needs its record first. No new
# start request goes out from here on, since this process can stop before it records the run.
self._child_run_registry.pause_starts()
try:
await self._child_run_registry.wait_for_starts_in_flight()

self.log.debug('Metamorphing the Actor run into target Actor %r.', target_actor_id)
await self.apify_client.run(self.configuration.actor_run_id).metamorph(
target_actor_id=target_actor_id,
run_input=run_input,
target_actor_build=target_actor_build,
content_type=content_type,
)
except BaseException:
self._child_run_registry.resume_starts()
raise

if custom_after_sleep:
await asyncio.sleep(custom_after_sleep.total_seconds())
Expand All @@ -1859,7 +1875,10 @@ async def reboot(
) -> None:
"""Internally reboot this Actor.

The system stops the current container and starts a new one, with the same run ID and default storages.
The system stops the current container and starts a new one, with the same run ID and default storages. The
recorded child runs keep running, and the new container gets them back from the child run registry. Before
the reboot, this method waits up to 10 seconds for the child run starts that are already sent, and it holds
back the ones that are not sent yet.

Args:
event_listeners_timeout: How long should the Actor wait for Actor event listeners to finish before exiting.
Expand Down Expand Up @@ -1909,11 +1928,17 @@ async def safe_dispatch(listener: Any, data: Any) -> None:
except TimeoutError:
self.log.warning('Pre-reboot event listeners did not finish within timeout; proceeding with reboot')

# The next process gets the child runs back from the registry, so every started run needs its record. No
# new start request goes out from here on, since this process can stop before it records the run.
self._child_run_registry.pause_starts()
await self._child_run_registry.wait_for_starts_in_flight()

self.log.debug('Rebooting the Actor run.')
await self.apify_client.run(self.configuration.actor_run_id).reboot()
except BaseException:
# Reset the flag so that a failed or cancelled reboot can be retried.
self._is_rebooting = False
self._child_run_registry.resume_starts()
raise

if custom_after_sleep:
Expand Down
108 changes: 93 additions & 15 deletions src/apify/_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import itertools
import json
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager
from logging import getLogger
from typing import TYPE_CHECKING, Any, NamedTuple
from weakref import WeakValueDictionary
Expand All @@ -18,7 +19,7 @@
from apify._utils import docs_group

if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
from collections.abc import AsyncGenerator, Awaitable, Callable

from apify_client import ApifyClientAsync
from apify_client._literals import ActorPermissionLevel
Expand All @@ -40,6 +41,9 @@
ABORT_WITH_PARENT_TIMEOUT_SECS = 10
"""How long aborting the child runs with the parent is waited for."""

STARTS_IN_FLIGHT_TIMEOUT_SECS = 10
"""How long a reboot, metamorph or exit of the parent waits for the start requests that are already sent."""

_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."""

Expand Down Expand Up @@ -355,6 +359,15 @@ def __init__(self, tracker: ChildRunTracker | None, *, warn_on_excessive_runs: b
"""Aborts the runs marked `abort_with_parent`. Once it exists, no new run marked `abort_with_parent` starts."""
self._start_ids = itertools.count()
self._warned_excessive_runs = False
self._starts_in_flight = 0
"""Number of start requests that are sent and whose runs are not recorded yet."""
self._no_starts_in_flight = asyncio.Event()
self._no_starts_in_flight.set()
self._starts_allowed = asyncio.Event()
"""Cleared while the parent reboots or metamorphs, when it could no longer record a new run."""
self._starts_allowed.set()
self._is_closed = False
"""Whether the parent is exiting, after which no run starts."""

@property
def is_enabled(self) -> bool:
Expand Down Expand Up @@ -421,14 +434,15 @@ async def find_or_start(
)

self._check_not_aborting(key, abort_with_parent=bool(abort_with_parent))
run = await start_run()
new_record = ChildRunRecord(
run_id=run.id,
status=run.status,
abort_with_parent=bool(abort_with_parent),
checksum=checksum,
)
await self._store(key, new_record)
async with self._start_in_flight(key):
run = await start_run()
new_record = ChildRunRecord(
run_id=run.id,
status=run.status,
abort_with_parent=bool(abort_with_parent),
checksum=checksum,
)
await self._store(key, new_record)
self._clients[key] = client
return run, True

Expand All @@ -455,11 +469,11 @@ async def start(
# The lock under a key of its own lets an abort of the child runs wait until the start is recorded.
async with self._key_locks.setdefault(f'start:{next(self._start_ids)}', asyncio.Lock()):
self._check_not_aborting('new child run', abort_with_parent=abort_with_parent)
run = await start_run()
key = run_key(run.id)
await self._store(
key, ChildRunRecord(run_id=run.id, status=run.status, abort_with_parent=abort_with_parent)
)
async with self._start_in_flight('new child run'):
run = await start_run()
key = run_key(run.id)
record = ChildRunRecord(run_id=run.id, status=run.status, abort_with_parent=abort_with_parent)
await self._store(key, record)
self._clients[key] = client
return run, key

Expand Down Expand Up @@ -545,14 +559,78 @@ async def _abort(self, key: str, record: ChildRunRecord, default_client: ApifyCl
if run.status in _ABORTED_STATUSES:
logger.info('Aborted child run "%s" with the parent', key, extra={'run_id': record.run_id})

@asynccontextmanager
async def _start_in_flight(self, name: str) -> AsyncGenerator[None]:
"""Count a start from the moment its request is sent until its run is recorded.

A parent that is about to reboot or metamorph holds the start back, and an exiting parent rejects it.

Raises:
RuntimeError: If the parent is exiting.
"""
# A parent that is about to reboot or metamorph sends no more start requests.
await self._starts_allowed.wait()
if self._is_closed:
raise RuntimeError(f'Child run "{name}" was not started, since this Actor is exiting.')
self._starts_in_flight += 1
self._no_starts_in_flight.clear()
try:
yield
finally:
self._starts_in_flight -= 1
if self._starts_in_flight == 0:
self._no_starts_in_flight.set()

def pause_starts(self) -> None:
"""Hold back the start requests that are not sent yet.

A parent that reboots or metamorphs calls this first. The process can stop before it records a run that it
starts from here on, and its next process would not know about the run.
"""
self._starts_allowed.clear()

def resume_starts(self) -> None:
"""Let the start requests go out again, after a reboot or a metamorph that failed."""
self._starts_allowed.set()

def close(self) -> None:
"""Reject every start that is not sent yet, since the parent is exiting."""
self._is_closed = True
# A start held back by a reboot or metamorph raises instead of waiting forever.
self._starts_allowed.set()

async def wait_for_starts_in_flight(self) -> None:
"""Wait until every start request that is already sent has its run recorded.

A parent that reboots, metamorphs or exits calls this first, so that its next process, or the target of the
metamorph, finds every started run in the registry. The wait takes at most `STARTS_IN_FLIGHT_TIMEOUT_SECS`.
"""
try:
async with asyncio.timeout(STARTS_IN_FLIGHT_TIMEOUT_SECS):
# A start can go out right after the last one is recorded, before this waiter wakes up.
while self._starts_in_flight:
await self._no_starts_in_flight.wait()
except TimeoutError:
logger.warning(
'Child run starts in flight did not finish in %d s, so their runs may not be recorded',
STARTS_IN_FLIGHT_TIMEOUT_SECS,
)

def _check_not_aborting(self, name: str, *, abort_with_parent: bool) -> None:
if abort_with_parent and self._abort_task is not None:
raise RuntimeError(
f'Child run "{name}" with `abort_with_parent` was not started, since this Actor run is being aborted.'
)

async def load(self) -> None:
"""Read the records through the tracker, replacing any read before. Does nothing with tracking off."""
"""Read the records through the tracker, replacing any read before, and allow starts again.

Reading does nothing with tracking off. The Actor calls this when it enters its context, also again after it
exited it in the same process.
"""
self._is_closed = False
self._abort_task = None
self._starts_allowed.set()
async with self._lock:
try:
if self._tracker is not None:
Expand Down
Loading