From 881d56b3e7dd887a4d3dc20d0735733e33a38a5f Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:05:18 +0100 Subject: [PATCH 1/2] feat: add a concurrency limit for child runs --- src/apify/_actor.py | 21 ++- src/apify/_child_runs.py | 168 ++++++++++++++++++++-- tests/unit/actor/test_actor_child_runs.py | 150 +++++++++++++++++++ 3 files changed, 327 insertions(+), 12 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index ade80270..f722b8f4 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -87,8 +87,8 @@ def _warn_child_runs_experimental() -> None: warnings.warn( - 'Child run features (`run_name`, `abort_with_parent`, `Actor.child_runs` and `child_run_tracker`) are ' - 'experimental. Their behavior and interface may change in future versions.', + 'Child run features (`run_name`, `abort_with_parent`, `Actor.child_runs`, `child_run_tracker` and ' + '`max_concurrent_child_runs`) are experimental. Their behavior and interface may change in future versions.', UserWarning, # This helper, the SDK method, and its `ensure_context` wrapper sit between the warning and the caller. stacklevel=4, @@ -161,6 +161,7 @@ def __init__( cleanup_timeout: timedelta = timedelta(seconds=30), child_run_tracker: ChildRunTracker | Literal['default'] | None = 'default', disable_excessive_child_run_warning: bool = False, + max_concurrent_child_runs: int | None = None, ) -> None: """Initialize a new instance. @@ -180,6 +181,13 @@ def __init__( behavior and interface may change in future versions. disable_excessive_child_run_warning: Whether to mute the warning logged once the child run registry holds many records. + max_concurrent_child_runs: How many child runs may be active at once, or `None` for no limit. At the + limit, `Actor.start`, `Actor.call`, `Actor.start_task` and `Actor.call_task` wait to start a new run, + in the order in which they were called, until another one finishes. A call that returns a recorded + run under its run name does not wait. It counts the recorded runs of earlier processes of this Actor + run too, but it holds only in the process that sets it, so set it in every process. Once this Actor run + is being aborted, a call that would have to wait raises a `RuntimeError`. It needs child run tracking. + The limit is experimental, so its behavior and interface may change in future versions. """ self._configuration = configuration self._configure_logging = configure_logging @@ -203,8 +211,13 @@ def __init__( child_run_tracker = KeyValueStoreChildRunTracker(self.open_key_value_store) elif child_run_tracker is not None: _warn_child_runs_experimental() + if max_concurrent_child_runs is not None: + _warn_child_runs_experimental() self._child_run_registry = ChildRunRegistry( - child_run_tracker, warn_on_excessive_runs=not disable_excessive_child_run_warning + child_run_tracker, + warn_on_excessive_runs=not disable_excessive_child_run_warning, + max_concurrent_runs=max_concurrent_child_runs, + default_client=lambda: self.apify_client, ) self._runs_with_redirected_log: set[str | None] = set() @@ -441,6 +454,7 @@ def __call__( cleanup_timeout: timedelta = timedelta(seconds=30), child_run_tracker: ChildRunTracker | Literal['default'] | None = 'default', disable_excessive_child_run_warning: bool = False, + max_concurrent_child_runs: int | None = None, ) -> Self: """Make a new Actor instance with a non-default configuration. @@ -456,6 +470,7 @@ def __call__( cleanup_timeout=cleanup_timeout, child_run_tracker=child_run_tracker, disable_excessive_child_run_warning=disable_excessive_child_run_warning, + max_concurrent_child_runs=max_concurrent_child_runs, ) @property diff --git a/src/apify/_child_runs.py b/src/apify/_child_runs.py index 3bc2a364..d62be92b 100644 --- a/src/apify/_child_runs.py +++ b/src/apify/_child_runs.py @@ -4,8 +4,9 @@ import hashlib import itertools import json +import math from abc import ABC, abstractmethod -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, suppress from logging import getLogger from typing import TYPE_CHECKING, Any, NamedTuple from weakref import WeakValueDictionary @@ -44,6 +45,9 @@ 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.""" +STATUS_MAX_AGE_SECS = 10 +"""How long an observed active status counts toward the concurrency limit before the run is fetched again.""" + _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.""" @@ -337,15 +341,49 @@ class ChildRunRegistry: and that write can still orphan the child, since nothing but the platform knows about it. """ - def __init__(self, tracker: ChildRunTracker | None, *, warn_on_excessive_runs: bool = True) -> None: + def __init__( + self, + tracker: ChildRunTracker | None, + *, + warn_on_excessive_runs: bool = True, + max_concurrent_runs: int | None = None, + default_client: Callable[[], ApifyClientAsync] | None = None, + ) -> None: """Initialize a new instance. Args: tracker: Storage of the records, or `None` to turn child run tracking off. warn_on_excessive_runs: Whether to log a warning once the registry holds too many records. + max_concurrent_runs: How many child runs may be active at once, or `None` for no limit. + default_client: Returns the client that fetches a run for the concurrency limit, unless the run was + started or looked up with its own client in this process. It is required with a limit. + + Raises: + ValueError: If `max_concurrent_runs` is not a positive integer, or is set with tracking off. """ + is_integer = isinstance(max_concurrent_runs, int) and not isinstance(max_concurrent_runs, bool) + if max_concurrent_runs is not None and (not is_integer or max_concurrent_runs < 1): + raise ValueError(f'`max_concurrent_child_runs` must be a positive integer, got {max_concurrent_runs!r}.') + if max_concurrent_runs is not None and tracker is None: + raise ValueError( + '`max_concurrent_child_runs` needs child run tracking, which is turned off with ' + '`child_run_tracker=None`.' + ) + if max_concurrent_runs is not None and default_client is None: + raise ValueError('The child run registry needs a default client to apply the concurrency limit.') + self._tracker = tracker self._warn_on_excessive_runs = warn_on_excessive_runs + self._max_concurrent_runs = max_concurrent_runs + self._default_client = default_client + self._admission_lock = asyncio.Lock() + """Admits the calls that wait for the concurrency limit one at a time, in the order in which they arrived.""" + self._capacity_changed = asyncio.Event() + """Set when a run may have stopped counting toward the concurrency limit, or the abort began.""" + self._status_observed_at: dict[str, float] = {} + """Event loop time at which this process last got the status of the run under each key from the API.""" + self._missing_keys: set[str] = set() + """Keys whose recorded run the API no longer knows, so the run does not count toward the limit.""" self._records: dict[str, ChildRunRecord] | None = None self._loaded = asyncio.Event() """Set once the Actor has read the records from the tracker, or has failed to.""" @@ -422,6 +460,7 @@ async def find_or_start( if abort_with_parent is not None: update['abort_with_parent'] = abort_with_parent updated_record = record.model_copy(update=update) + self._mark_observed(key, run.status) if updated_record != record: await self._store(key, updated_record) self._clients[key] = client @@ -501,7 +540,10 @@ async def update(self, key: str, run: Run) -> None: run: The run as just returned by the API. Nothing is recorded unless it is the run under `key`. """ record = self._get_records().get(key) - if record is None or record.run_id != run.id or record.status == run.status: + if record is None or record.run_id != run.id: + return + self._mark_observed(key, run.status) + if record.status == run.status: return await self._store(key, record.model_copy(update={'status': run.status})) @@ -519,6 +561,8 @@ async def abort_runs_with_parent(self, client: ApifyClientAsync) -> None: """ if self._abort_task is None: self._abort_task = asyncio.create_task(self._abort_runs_with_parent(client)) + # The calls that wait for the concurrency limit hold the locks that the abort waits for, and give up now. + self._capacity_changed.set() try: await asyncio.wait_for(asyncio.shield(self._abort_task), ABORT_WITH_PARENT_TIMEOUT_SECS) except TimeoutError: @@ -563,15 +607,23 @@ async def _abort(self, key: str, record: ChildRunRecord, default_client: ApifyCl 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. + The start first waits for the concurrency limit. 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. + RuntimeError: If the parent is exiting, or the start would have to wait for the concurrency limit while + this Actor run is being aborted. """ - # 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.') + while True: + # A parent that is about to reboot or metamorph sends no more start requests. + await self._starts_allowed.wait() + await self._wait_for_capacity(name) + if self._is_closed: + raise RuntimeError(f'Child run "{name}" was not started, since this Actor is exiting.') + # A reboot or metamorph may have begun during the wait for the concurrency limit. + if self._starts_allowed.is_set(): + break + # Nothing is awaited between the check of the limit and this count, so no other start takes the same place. self._starts_in_flight += 1 self._no_starts_in_flight.clear() try: @@ -580,6 +632,103 @@ async def _start_in_flight(self, name: str) -> AsyncGenerator[None]: self._starts_in_flight -= 1 if self._starts_in_flight == 0: self._no_starts_in_flight.set() + self._capacity_changed.set() + + async def _wait_for_capacity(self, name: str) -> None: + """Wait until fewer child runs than the concurrency limit are active. + + The active runs are the recorded runs with an active status and the starts in flight. A recorded status + that this process did not get from the API in the last `STATUS_MAX_AGE_SECS` is fetched again before it is + counted, which covers every status loaded from an earlier process. + + Raises: + RuntimeError: If the start would have to wait while this Actor run is being aborted. + """ + if self._max_concurrent_runs is None: + return + + async with self._admission_lock: + is_waiting = False + while True: + if self._count_active() < self._max_concurrent_runs: + return + # A stale status can only make the count too high, so the runs are fetched only at the limit. + if await self._refresh_stale_statuses(): + continue + if self._abort_task is not None: + raise RuntimeError( + f'Child run "{name}" was not started, since this Actor run is being aborted and the limit of ' + f'{self._max_concurrent_runs} concurrent child runs is reached.' + ) + if not is_waiting: + is_waiting = True + logger.info( + 'Child run "%s" is waiting, since %d child runs are active', name, self._max_concurrent_runs + ) + self._capacity_changed.clear() + # Wake up without a change as well, to fetch the runs whose status got stale. + with suppress(TimeoutError): + await asyncio.wait_for(self._capacity_changed.wait(), STATUS_MAX_AGE_SECS) + + def _count_active(self) -> int: + active = self._starts_in_flight + for key, record in self._get_records().items(): + if key not in self._missing_keys and record.status not in TERMINAL_RUN_STATUSES: + active += 1 + return active + + def _mark_observed(self, key: str, status: str) -> None: + """Note that the API just returned the run under `key` with `status`.""" + self._status_observed_at[key] = asyncio.get_running_loop().time() + self._missing_keys.discard(key) + if status in TERMINAL_RUN_STATUSES: + self._capacity_changed.set() + + async def _refresh_stale_statuses(self) -> bool: + """Fetch the recorded runs whose active status this process did not get from the API recently. + + A run that finished without a call waiting for it stops counting toward the concurrency limit this way. + + Returns: + Whether a run stopped counting toward the concurrency limit. + """ + if self._default_client is None: + return False + + loop = asyncio.get_running_loop() + stale_keys = [ + key + for key, record in self._get_records().items() + if record.status not in TERMINAL_RUN_STATUSES + and loop.time() - self._status_observed_at.get(key, -math.inf) >= STATUS_MAX_AGE_SECS + ] + if not stale_keys: + return False + + default_client = self._default_client() + records = self._get_records() + fetches = [self._clients.get(key, default_client).run(records[key].run_id).get() for key in stale_keys] + fetched_runs = await asyncio.gather(*fetches, return_exceptions=True) + + freed = False + for key, fetched_run in zip(stale_keys, fetched_runs, strict=True): + self._status_observed_at[key] = loop.time() + if isinstance(fetched_run, BaseException): + # The run keeps counting, and a later refresh fetches it again. + logger.warning('Failed to fetch child run "%s" for the concurrency limit', key, exc_info=fetched_run) + continue + if fetched_run is None: + # The run does not count while the API does not return it, and a later refresh fetches it again. + freed = freed or key not in self._missing_keys + self._missing_keys.add(key) + continue + record = records.get(key) + # A call under the key may have replaced the run in the meantime. + if record is None or record.run_id != fetched_run.id or record.status == fetched_run.status: + continue + freed = freed or fetched_run.status in TERMINAL_RUN_STATUSES + await self._store(key, record.model_copy(update={'status': fetched_run.status})) + return freed def pause_starts(self) -> None: """Hold back the start requests that are not sent yet. @@ -654,6 +803,7 @@ async def _store(self, key: str, record: ChildRunRecord) -> None: raise RuntimeError('Child run tracking is turned off.') async with self._lock: records[key] = record + self._mark_observed(key, record.status) self._warn_if_excessive() await self._tracker.store_run(key, record) diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 52f2f404..b9b2e758 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -2146,3 +2146,153 @@ async def start_run(*_args: Any, **_kwargs: Any) -> Run: keys = [child_run.key for child_run in Actor.child_runs] assert keys == ['run:new-run'] + + +def make_starter(order: list[str]) -> Any: + """Return a replacement for a start request that starts a run named after its input and records the order.""" + + def start(*_args: Any, run_input: Any = None, **_kwargs: Any) -> Run: + order.append(run_input['name']) + return make_run(f'{run_input["name"]}-run', 'READY') + + return start + + +async def test_concurrency_limit_waits_for_a_run_to_finish(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: + """At the limit, a start waits until a recorded run finishes.""" + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + + async with Actor(max_concurrent_child_runs=1): + await Actor.start('some-actor', {'name': 'first'}) + second = asyncio.create_task(Actor.start('some-actor', {'name': 'second'})) + await asyncio.sleep(0.05) + assert not second.done() + await Actor._child_run_registry.update('run:first-run', make_run('first-run', 'SUCCEEDED')) + await asyncio.wait_for(second, timeout=1) + + assert order == ['first', 'second'] + + +async def test_concurrency_limit_admits_waiting_calls_in_arrival_order( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """Calls waiting for the limit start their runs in the order in which they were made.""" + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + + async with Actor(max_concurrent_child_runs=1): + await Actor.start('some-actor', {'name': 'first'}) + waiting = [] + for name in ('second', 'third', 'fourth'): + waiting.append(asyncio.create_task(Actor.start('some-actor', {'name': name}))) + await asyncio.sleep(0) + for previous in ('first', 'second', 'third'): + await asyncio.sleep(0.02) + await Actor._child_run_registry.update(f'run:{previous}-run', make_run(f'{previous}-run', 'SUCCEEDED')) + await asyncio.wait_for(asyncio.gather(*waiting), timeout=1) + + assert order == ['first', 'second', 'third', 'fourth'] + + +async def test_concurrency_limit_rejects_waiting_call_once_aborting( + apify_client_async_patcher: ApifyClientAsyncPatcher, apify_event_manager: ApifyEventManager +) -> None: + """Once the parent is being aborted, a call waiting for the limit raises a `RuntimeError` and starts no run.""" + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('first-run', 'RUNNING')) + + async with Actor(max_concurrent_child_runs=1): + await Actor.start('some-actor', {'name': 'first'}) + second = asyncio.create_task(Actor.start('some-actor', {'name': 'second'})) + await asyncio.sleep(0.05) + apify_event_manager.emit(event=Event.ABORTING, event_data=EventAbortingData()) + await apify_event_manager.wait_for_all_listeners_to_complete() + with pytest.raises(RuntimeError, match='limit of 1 concurrent child runs'): + await asyncio.wait_for(second, timeout=1) + + assert order == ['first'] + + +async def test_concurrency_limit_does_not_hold_back_a_recorded_named_run( + apify_client_async_patcher: ApifyClientAsyncPatcher, +) -> None: + """At the limit, a named call that returns its recorded run does not wait.""" + 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(max_concurrent_child_runs=1): + first = await Actor.start('some-actor', run_name='scrape-eu') + second = await asyncio.wait_for(Actor.start('some-actor', run_name='scrape-eu'), timeout=1) + + assert first.id == second.id + assert len(apify_client_async_patcher.calls['actor']['start']) == 1 + + +@pytest.mark.parametrize( + ('fetched_status', 'expected_order'), + [ + pytest.param('SUCCEEDED', ['new'], id='recorded run finished'), + pytest.param(None, ['new'], id='recorded run missing'), + ], +) +async def test_concurrency_limit_fetches_runs_recorded_by_earlier_process( + apify_client_async_patcher: ApifyClientAsyncPatcher, fetched_status: str | None, expected_order: list[str] +) -> None: + """An active status loaded from an earlier process is fetched again before it counts toward the limit.""" + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + fetched_run = make_run('old-run', fetched_status) if fetched_status else None + apify_client_async_patcher.patch('run', 'get', return_value=fetched_run) + + async with Actor: + kvs = await Actor.open_key_value_store() + records = {'run:old-run': {'runId': 'old-run', 'status': 'RUNNING', 'abortWithParent': False}} + await kvs.set_value(CHILD_RUNS_KEY, stored_registry(runs=records)) + + async with Actor(max_concurrent_child_runs=1): + await asyncio.wait_for(Actor.start('some-actor', {'name': 'new'}), timeout=1) + + assert order == expected_order + assert len(apify_client_async_patcher.calls['run']['get']) == 1 + + +async def test_concurrency_limit_fetches_stale_status_of_a_run( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """A waiting call fetches a run whose active status got stale, and starts once the run turns out finished.""" + monkeypatch.setattr(_child_runs, 'STATUS_MAX_AGE_SECS', 0.05) + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('first-run', 'SUCCEEDED')) + + async with Actor(max_concurrent_child_runs=1): + await Actor.start('some-actor', {'name': 'first'}) + await asyncio.wait_for(Actor.start('some-actor', {'name': 'second'}), timeout=1) + [first, second] = Actor.child_runs + + assert order == ['first', 'second'] + assert first.record.status == 'SUCCEEDED' + assert second.record.status == 'READY' + + +@pytest.mark.parametrize( + 'value', + [ + pytest.param(0, id='zero'), + pytest.param(-1, id='negative'), + pytest.param(True, id='bool'), + pytest.param(1.5, id='float'), + ], +) +def test_concurrency_limit_rejects_invalid_value(value: Any) -> None: + """`max_concurrent_child_runs` must be a positive integer.""" + with pytest.raises(ValueError, match='must be a positive integer'): + Actor(max_concurrent_child_runs=value) + + +def test_concurrency_limit_needs_tracking() -> None: + """`max_concurrent_child_runs` with child run tracking off raises a `ValueError`.""" + with pytest.raises(ValueError, match='needs child run tracking'): + Actor(child_run_tracker=None, max_concurrent_child_runs=2) From 162d0e22ad5f1c12c23067def6aab82e2a39de85 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 27 Nov 2026 15:19:24 +0100 Subject: [PATCH 2/2] fix: resolve `timeout='inherit'` when the start request goes out --- src/apify/_actor.py | 22 ++++++++++++++-------- tests/unit/actor/test_actor_child_runs.py | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index f722b8f4..9404460e 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1247,6 +1247,7 @@ async def start( run, _, _ = await self._start_child_run( run_name=run_name, client=client, + timeout=timeout, start_run=partial( actor_client.start, run_input=run_input, @@ -1256,7 +1257,6 @@ async def start( max_total_charge_usd=max_total_charge_usd, restart_on_error=restart_on_error, memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), force_permission_level=force_permission_level, webhooks=to_client_representations(webhooks), ), @@ -1451,6 +1451,7 @@ async def call( started_run, key, is_new = await self._start_child_run( run_name=run_name, client=client, + timeout=timeout, start_run=partial( actor_client.start, run_input=run_input, @@ -1460,7 +1461,6 @@ async def call( max_total_charge_usd=max_total_charge_usd, restart_on_error=restart_on_error, memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), force_permission_level=force_permission_level, webhooks=to_client_representations(webhooks), ), @@ -1507,7 +1507,8 @@ async def _start_child_run( *, run_name: str | None, client: ApifyClientAsync, - start_run: Callable[[], Awaitable[Run]], + start_run: Callable[..., Awaitable[Run]], + timeout: timedelta | Literal['inherit'] | None, actor_id: str | None = None, task_id: str | None = None, run_input: Any = None, @@ -1524,13 +1525,18 @@ async def _start_child_run( The run, its key in the child run registry (`None` with child run tracking off), and whether it was newly started. """ + + def start_run_now(**kwargs: Any) -> Awaitable[Run]: + # `inherit` gets the time left when the request goes out, after any wait for the concurrency limit. + return start_run(run_timeout=self._resolve_run_timeout(timeout), **kwargs) + if not self._child_run_registry.is_enabled: - return await start_run(), None, True + return await start_run_now(), None, True is_implicit = run_name is None and self.configuration.auto_memoize_child_runs if run_name is None and not is_implicit: run, key = await self._child_run_registry.start( - client=client, start_run=start_run, abort_with_parent=bool(abort_with_parent) + client=client, start_run=start_run_now, abort_with_parent=bool(abort_with_parent) ) return run, key, True @@ -1548,7 +1554,7 @@ async def _start_child_run( key, checksum=checksum, client=client, - start_run=start_run, + start_run=start_run_now, abort_with_parent=abort_with_parent, ) return run, key, is_new @@ -1690,6 +1696,7 @@ async def start_task( run, _, _ = await self._start_child_run( run_name=run_name, client=client, + timeout=timeout, start_run=partial( task_client.start, task_input=task_input, @@ -1698,7 +1705,6 @@ async def start_task( max_total_charge_usd=max_total_charge_usd, restart_on_error=restart_on_error, memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), ), task_id=task_id, @@ -1795,6 +1801,7 @@ async def call_task( started_run, key, is_new = await self._start_child_run( run_name=run_name, client=client, + timeout=timeout, start_run=partial( task_client.start, task_input=task_input, @@ -1803,7 +1810,6 @@ async def call_task( max_total_charge_usd=max_total_charge_usd, restart_on_error=restart_on_error, memory_mbytes=memory_mbytes, - run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), # A request that times out is retried, and a retried start request can start a second run. timeout='no_timeout', diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index b9b2e758..39aaa14e 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -2296,3 +2296,24 @@ def test_concurrency_limit_needs_tracking() -> None: """`max_concurrent_child_runs` with child run tracking off raises a `ValueError`.""" with pytest.raises(ValueError, match='needs child run tracking'): Actor(child_run_tracker=None, max_concurrent_child_runs=2) + + +async def test_inherited_timeout_is_resolved_when_the_start_request_goes_out( + apify_client_async_patcher: ApifyClientAsyncPatcher, monkeypatch: pytest.MonkeyPatch +) -> None: + """A call that waits for the concurrency limit gives the child the time left when its start request goes out.""" + order: list[str] = [] + apify_client_async_patcher.patch('actor', 'start', replacement_method=make_starter(order)) + remaining_time = Mock(return_value=timedelta(minutes=10)) + + async with Actor(max_concurrent_child_runs=1): + monkeypatch.setattr(Actor, '_get_remaining_time', remaining_time) + await Actor.start('some-actor', {'name': 'first'}, timeout='inherit') + second = asyncio.create_task(Actor.start('some-actor', {'name': 'second'}, timeout='inherit')) + await asyncio.sleep(0.05) + remaining_time.return_value = timedelta(minutes=4) + await Actor._child_run_registry.update('run:first-run', make_run('first-run', 'SUCCEEDED')) + await asyncio.wait_for(second, timeout=1) + + run_timeouts = [kwargs['run_timeout'] for _, kwargs in apify_client_async_patcher.calls['actor']['start']] + assert run_timeouts == [timedelta(minutes=10), timedelta(minutes=4)]