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
38 changes: 29 additions & 9 deletions src/apify/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1842,7 +1842,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 @@ -1864,13 +1866,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 @@ -1884,7 +1895,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 @@ -1934,11 +1948,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
83 changes: 69 additions & 14 deletions src/apify/_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import hashlib
import json
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import timedelta
from logging import getLogger
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 Awaitable, Callable, Generator
from decimal import Decimal

from apify_client import ApifyClientAsync
Expand Down Expand Up @@ -47,6 +48,9 @@
_ABORT_RECORD_TIMEOUT = timedelta(seconds=2)
"""How long the write of what the abort requests returned is waited for, after the abort itself."""

_STARTS_IN_FLIGHT_TIMEOUT = timedelta(seconds=10)
"""How long a reboot or metamorph 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 @@ -332,6 +336,13 @@ def __init__(
"""Whether this Actor run is being gracefully aborted, after which no run marked `abort_with_parent` starts."""
self._abort_task: asyncio.Task[None] | None = None
"""The abort of the child runs with the parent, once the parent is being gracefully aborted."""
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 ends its process on its own, when it could no longer record a new run."""
self._starts_allowed.set()

async def find_or_start(
self,
Expand Down Expand Up @@ -432,22 +443,66 @@ async def find_or_start(
'aborted.'
)

run = await start_run()
new_record = ChildRunRecord(
run_id=run.id,
run_name=key.key if key.kind == 'named' else None,
status=run.status,
checksum=checksum,
abort_with_parent=abort_with_parent,
resurrect_with_parent=resurrect_with_parent,
# An abort that started while the start request was in flight waits for this key, and
# then aborts the run.
aborted_with_parent=abort_with_parent and self._is_abort_in_progress(),
)
await self._save(key, new_record)
# A parent that is about to reboot or metamorph sends no more start requests.
await self._starts_allowed.wait()
with self._start_in_flight():
run = await start_run()
new_record = ChildRunRecord(
run_id=run.id,
run_name=key.key if key.kind == 'named' else None,
status=run.status,
checksum=checksum,
abort_with_parent=abort_with_parent,
resurrect_with_parent=resurrect_with_parent,
# An abort that started while the start request was in flight waits for this key, and
# then aborts the run.
aborted_with_parent=abort_with_parent and self._is_abort_in_progress(),
)
await self._save(key, new_record)
self._clients[key] = client
return run, True

@contextmanager
def _start_in_flight(self) -> Generator[None]:
"""Count a start from the moment its request is sent until its run is recorded."""
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 ends its process on its own, by a reboot or a metamorph, calls this first. The process can stop
before it records a run that it starts from here on, and its next process would then start the run again.
"""
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()

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 ends its process on its own, by a reboot or a metamorph, calls this first, so that its next
process finds every started run in the registry. The wait takes at most `_STARTS_IN_FLIGHT_TIMEOUT`.
"""
try:
async with asyncio.timeout(_STARTS_IN_FLIGHT_TIMEOUT.total_seconds()):
# 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 %.3g seconds, so their runs may not be recorded',
_STARTS_IN_FLIGHT_TIMEOUT.total_seconds(),
)

async def _resurrect_with_parent(
self, key: ChildRunKey, run_client: RunClientAsync, run: Run
) -> tuple[Run | None, bool]:
Expand Down
197 changes: 197 additions & 0 deletions tests/unit/actor/test_actor_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2238,6 +2238,103 @@ async def test_new_run_records_resurrect_with_parent(
assert child_run.record.aborted_with_parent is False


@pytest.mark.parametrize(
('method', 'args'),
[
pytest.param('reboot', (), id='reboot'),
pytest.param('metamorph', ('target-actor',), id='metamorph'),
],
)
async def test_reboot_and_metamorph_wait_for_starts_in_flight(
apify_client_async_patcher: ApifyClientAsyncPatcher,
monkeypatch: pytest.MonkeyPatch,
method: str,
args: tuple[str, ...],
) -> None:
"""A reboot or metamorph is requested only after a child run start in flight is recorded."""
events = list[str]()
started = asyncio.Event()
release = asyncio.Event()

async def start_run(*_args: Any, **_kwargs: Any) -> Run:
started.set()
await release.wait()
events.append('started')
return make_run('new-run', 'READY')

async def end_process(*_args: Any, **_kwargs: Any) -> None:
kvs = await Actor.open_key_value_store()
stored = await kvs.get_value(CHILD_RUNS_KEY)
recorded = sorted((stored or {}).get('named', {}))
events.append(f'{method} with {recorded}')

apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run)
apify_client_async_patcher.patch('run', method, replacement_method=end_process)

async with Actor:
# Only the check in the method sees the platform, so the storages stay local.
monkeypatch.setattr(_ActorType, 'is_at_home', lambda _self: True)
Actor.configuration.actor_run_id = 'some-run-id'
start_task = asyncio.create_task(Actor.start('some-actor', run_name='scrape-eu'))
await started.wait()
end_task = asyncio.create_task(getattr(Actor, method)(*args, custom_after_sleep=timedelta(0)))
await asyncio.sleep(0.05)
assert events == []
release.set()
await asyncio.gather(start_task, end_task)

assert events == ['started', f"{method} with ['scrape-eu']"]


async def test_reboot_stops_waiting_for_starts_in_flight_after_the_time_limit(
apify_client_async_patcher: ApifyClientAsyncPatcher,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A reboot goes ahead with a warning when a child run start in flight does not finish in time."""
monkeypatch.setattr(_child_runs, '_STARTS_IN_FLIGHT_TIMEOUT', timedelta(milliseconds=50))
started = asyncio.Event()
release = asyncio.Event()

async def start_run(*_args: Any, **_kwargs: Any) -> Run:
started.set()
await release.wait()
return make_run('new-run', 'READY')

apify_client_async_patcher.patch('actor', 'start', replacement_method=start_run)
apify_client_async_patcher.patch('run', 'reboot', return_value=None)

async with Actor:
# Only the check in the method sees the platform, so the storages stay local.
monkeypatch.setattr(_ActorType, 'is_at_home', lambda _self: True)
Actor.configuration.actor_run_id = 'some-run-id'
start_task = asyncio.create_task(Actor.start('some-actor', run_name='scrape-eu'))
await started.wait()
await Actor.reboot(custom_after_sleep=timedelta(0))
release.set()
await start_task

assert len(apify_client_async_patcher.calls['run']['reboot']) == 1
assert 'Child run starts in flight did not finish in 0.05 seconds' in caplog.text


async def test_reboot_does_not_wait_without_starts_in_flight(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A reboot is requested right away when every started child run is recorded."""
apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY'))
apify_client_async_patcher.patch('run', 'reboot', return_value=None)

async with Actor:
# Only the check in the method sees the platform, so the storages stay local.
monkeypatch.setattr(_ActorType, 'is_at_home', lambda _self: True)
Actor.configuration.actor_run_id = 'some-run-id'
await Actor.start('some-actor', run_name='scrape-eu')
await asyncio.wait_for(Actor.reboot(custom_after_sleep=timedelta(0)), timeout=1)

assert len(apify_client_async_patcher.calls['run']['reboot']) == 1


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()
Expand Down Expand Up @@ -2532,3 +2629,103 @@ async def test_slow_registry_write_does_not_stop_the_abort_of_child_runs(

client.run.return_value.abort.assert_awaited_once_with(gracefully=True)
assert 'Recording the child runs to abort with the parent did not finish' in caplog.text


async def test_wait_for_starts_in_flight_covers_a_start_sent_right_after_another_is_recorded() -> None:
"""The wait before a reboot lasts until no start is in flight, also when one start follows another at once."""
client = Mock()
release_first = asyncio.Event()
release_second = asyncio.Event()

async def start_first() -> Run:
await release_first.wait()
return make_run('first-run', 'READY')

async def start_second() -> Run:
await release_second.wait()
return make_run('second-run', 'READY')

async with Actor:
registry = ChildRunRegistry(Actor.open_key_value_store)
await registry.load()

async def start_both() -> None:
await registry.find_or_start(
ChildRunKey('named', 'first'), checksum='checksum', client=client, start_run=start_first
)
await registry.find_or_start(
ChildRunKey('named', 'second'), checksum='checksum', client=client, start_run=start_second
)

starts = asyncio.create_task(start_both())
await asyncio.sleep(0)
waiter = asyncio.create_task(registry.wait_for_starts_in_flight())
await asyncio.sleep(0)
release_first.set()
await asyncio.sleep(0.05)
assert not waiter.done()
release_second.set()
await asyncio.wait_for(asyncio.gather(starts, waiter), timeout=1)
recorded = registry.child_runs(client).named

assert recorded.keys() == {'first', 'second'}


async def test_failed_start_does_not_count_as_a_start_in_flight() -> None:
"""A start request that fails does not make a later reboot wait."""
client = Mock()

async with Actor:
registry = ChildRunRegistry(Actor.open_key_value_store)
await registry.load()
with pytest.raises(RuntimeError, match='start failed'):
await registry.find_or_start(
ChildRunKey('named', 'scrape-eu'),
checksum='checksum',
client=client,
start_run=AsyncMock(side_effect=RuntimeError('start failed')),
)
await asyncio.wait_for(registry.wait_for_starts_in_flight(), timeout=1)


async def test_paused_starts_send_no_request_until_they_are_resumed() -> None:
"""A start made after the parent began to reboot or metamorph sends its request only when starts are resumed."""
client = Mock()
start_run = AsyncMock(return_value=make_run('new-run', 'READY'))

async with Actor:
registry = ChildRunRegistry(Actor.open_key_value_store)
await registry.load()
registry.pause_starts()
start = asyncio.create_task(
registry.find_or_start(
ChildRunKey('named', 'scrape-eu'), checksum='checksum', client=client, start_run=start_run
)
)
await asyncio.sleep(0.05)
start_run.assert_not_awaited()
await asyncio.wait_for(registry.wait_for_starts_in_flight(), timeout=1)
registry.resume_starts()
run, _ = await asyncio.wait_for(start, timeout=1)

assert run.id == 'new-run'


async def test_failed_reboot_resumes_child_run_starts(
apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A reboot request that fails lets the child run starts go out again."""
apify_client_async_patcher.patch('actor', 'start', return_value=make_run('new-run', 'READY'))
apify_client_async_patcher.patch(
'run', 'reboot', replacement_method=Mock(side_effect=RuntimeError('reboot failed'))
)

async with Actor:
# Only the check in the method sees the platform, so the storages stay local.
monkeypatch.setattr(_ActorType, 'is_at_home', lambda _self: True)
Actor.configuration.actor_run_id = 'some-run-id'
with pytest.raises(RuntimeError, match='reboot failed'):
await Actor.reboot(custom_after_sleep=timedelta(0))
run = await asyncio.wait_for(Actor.start('some-actor', run_name='scrape-eu'), timeout=1)

assert run.id == 'new-run'