From 00686472cb930b463380e545e94ac641eae62a68 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:05:18 +0100 Subject: [PATCH] fix: wait for child run starts before a reboot, metamorph or exit --- src/apify/_actor.py | 43 ++++- src/apify/_child_runs.py | 108 +++++++++-- tests/unit/actor/test_actor_child_runs.py | 223 ++++++++++++++++++++++ 3 files changed, 350 insertions(+), 24 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 8bbc66ea..ade80270 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -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. @@ -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() @@ -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 @@ -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()) @@ -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. @@ -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: diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index dee9d442..3bc2a364 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -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 @@ -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 @@ -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.""" @@ -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: @@ -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 @@ -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 @@ -545,6 +559,63 @@ 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( @@ -552,7 +623,14 @@ def _check_not_aborting(self, name: str, *, abort_with_parent: bool) -> None: ) 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: diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 0b82dc6e..52f2f404 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -1923,3 +1923,226 @@ async def test_named_call_abort_with_parent_none_keeps_recorded_value( [child_run] = Actor.child_runs assert child_run.record.abort_with_parent is recorded_value + + +@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('runs', {})) + 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 ['name: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_SECS', 0.05) + 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 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_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(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + await registry.load() + + async def start_both() -> None: + await registry.find_or_start(name_key('first'), checksum='checksum', client=client, start_run=start_first) + await registry.find_or_start(name_key('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 = named_child_runs(registry.child_runs(client)) + + 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(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + await registry.load() + with pytest.raises(RuntimeError, match='start failed'): + await registry.find_or_start( + name_key('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(KeyValueStoreChildRunTracker(Actor.open_key_value_store)) + await registry.load() + registry.pause_starts() + start = asyncio.create_task( + registry.find_or_start(name_key('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' + + +async def test_exit_waits_for_start_in_flight_and_rejects_new_starts( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """An exit waits until a child run start in flight is recorded, and a start made during the exit raises.""" + 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) + + actor = Actor(exit_process=False) + await actor.init() + start_task = asyncio.create_task(actor.start('some-actor')) + await started.wait() + exit_task = asyncio.create_task(actor.exit()) + await asyncio.sleep(0.05) + assert not exit_task.done() + with pytest.raises(RuntimeError, match='this Actor is exiting'): + await actor.start('some-actor') + release.set() + await asyncio.gather(start_task, exit_task) + + async with Actor: + keys = [child_run.key for child_run in Actor.child_runs] + + assert keys == ['run:new-run']