From d864d43548d8876cedce76486aedb7ec4c94acd3 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:20:11 +0100 Subject: [PATCH 1/7] feat: stream the run log in `Actor.call_task` --- docs/02_concepts/09_logging.mdx | 2 + src/apify/_actor.py | 43 +++++++---- tests/unit/actor/test_actor_child_runs.py | 43 +++++++++-- tests/unit/actor/test_actor_helpers.py | 90 ++++++++++++++++++++--- 4 files changed, 147 insertions(+), 31 deletions(-) diff --git a/docs/02_concepts/09_logging.mdx b/docs/02_concepts/09_logging.mdx index 80712da22..93399b876 100644 --- a/docs/02_concepts/09_logging.mdx +++ b/docs/02_concepts/09_logging.mdx @@ -94,6 +94,8 @@ In some situations, one Actor is going to start one or more other Actors and wai Typical use case for log redirection is to call another Actor using the `Actor.call` method. This method has an optional `logger` argument, which is by default set to the `default` literal. This means that the logs of the called Actor will be automatically redirected to the parent Actor's logs with default formatting and filtering. If you set the `logger` argument to `None`, then no log redirection happens. The third option is to pass your own `Logger` instance with the possibility to define your own formatter, filter, and handler. Below you can see those three possible ways of log redirection when starting another Actor run through `Actor.call`. +The `Actor.call_task` method has the same `logger` argument, with the same default. + {RedirectLog} diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 3e650c056..fe53a9c1d 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1477,20 +1477,31 @@ async def _wait_for_child_run( if run.status == 'SUCCEEDED': return run - if not logger: - finished_run = await run_client.wait_for_finish(wait_duration=wait) - else: - to_logger = None if logger == 'default' else logger - status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) - streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) - - async with status_redirector, streamed_log: - finished_run = await run_client.wait_for_finish(wait_duration=wait) + finished_run = await self._wait_for_run(run_client, wait=wait, logger=logger, from_start=from_start) if finished_run is not None: await self._child_run_registry.update(name, finished_run) return finished_run + async def _wait_for_run( + self, + run_client: RunClientAsync, + *, + wait: timedelta | None, + logger: logging.Logger | Literal['default'] | None, + from_start: bool, + ) -> Run | None: + """Wait for a run to finish, and redirect its log and status messages to `logger` meanwhile.""" + if not logger: + return await run_client.wait_for_finish(wait_duration=wait) + + to_logger = None if logger == 'default' else logger + status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) + streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) + + async with status_redirector, streamed_log: + return await run_client.wait_for_finish(wait_duration=wait) + @_ensure_context async def start_task( self, @@ -1608,6 +1619,7 @@ async def call_task( timeout: timedelta | Literal['inherit'] | None = None, webhooks: list[Webhook] | None = None, wait: timedelta | None = None, + logger: logging.Logger | Literal['default'] | None = 'default', token: str | None = None, run_name: str | None = None, abort_with_parent: bool = False, @@ -1640,6 +1652,9 @@ async def call_task( be used to receive a notification, e.g. when the Actor finished or failed. If you already have a webhook set up for the Actor, you do not have to add it again here. wait: The maximum time the server waits for the run to finish. If not provided, waits indefinitely. + logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined + default logger will be used. Setting `None` will disable any log propagation. Passing custom logger + will redirect logs to the provided logger. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the default key-value store, so after a migration or resurrection of this Actor the same call reattaches to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is @@ -1670,7 +1685,8 @@ async def call_task( task_client = client.task(task_id) if run_name is None: - run = await task_client.call( + # The client's `call` cannot redirect the log of the run, so the run is started and waited for here. + started_run = await task_client.start( task_input=task_input, build=build, max_items=max_items, @@ -1679,10 +1695,10 @@ async def call_task( memory_mbytes=memory_mbytes, run_timeout=self._resolve_run_timeout(timeout), webhooks=to_client_representations(webhooks), - wait_duration=wait, ) + run = await self._wait_for_run(client.run(started_run.id), wait=wait, logger=logger, from_start=True) else: - started_run, _ = await self._find_or_start_child_run( + started_run, is_new = await self._find_or_start_child_run( run_name, task_id=task_id, run_input=task_input, @@ -1706,8 +1722,9 @@ async def call_task( timeout=timeout, abort_with_parent=abort_with_parent, ) + # The earlier attempt of this call already streamed the log of a reattached or resurrected run. run = await self._wait_for_child_run( - run_name, client.run(started_run.id), started_run, wait=wait, logger=None, from_start=False + run_name, client.run(started_run.id), started_run, wait=wait, logger=logger, from_start=is_new ) if run is None: diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 48fe1842b..af8526eed 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -413,7 +413,7 @@ async def test_named_call_task_records_run_in_kvs(apify_client_async_patcher: Ap apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - run = await Actor.call_task('some-task', run_name='scrape-eu') + run = await Actor.call_task('some-task', run_name='scrape-eu', logger=None) kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) @@ -430,13 +430,42 @@ async def test_named_call_task_waits_for_reattached_run(apify_client_async_patch async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - run = await Actor.call_task('some-task', run_name='scrape-eu') + run = await Actor.call_task('some-task', run_name='scrape-eu', logger=None) assert run.id == 'old-run' assert run.status == 'SUCCEEDED' assert apify_client_async_patcher.calls['task']['start'] == [] +@pytest.mark.parametrize( + ('is_recorded', 'from_start'), + [ + pytest.param(False, True, id='new run'), + pytest.param(True, False, id='reattached run'), + ], +) +async def test_named_call_task_streams_run_log( + apify_client_async_patcher: ApifyClientAsyncPatcher, *, is_recorded: bool, from_start: bool +) -> None: + """A named task call streams the log of a new run from the start, and only the new lines of a reattached run.""" + streamed_log = MagicMock() + get_streamed_log = Mock(return_value=streamed_log) + apify_client_async_patcher.patch('task', 'start', return_value=make_run('some-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('some-run', 'RUNNING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('some-run', 'SUCCEEDED')) + apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) + + async with Actor: + if is_recorded: + await record_child_run('scrape-eu', 'some-run', actor_id=None, task_id='some-task') + run = await Actor.call_task('some-task', run_name='scrape-eu') + + assert run.status == 'SUCCEEDED' + assert get_streamed_log.call_args.kwargs['from_start'] is from_start + streamed_log.__aenter__.assert_awaited_once() + + async def test_named_call_task_resurrects_recorded_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """A named task call resurrects an aborted run with its own options.""" apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) @@ -446,7 +475,7 @@ async def test_named_call_task_resurrects_recorded_run(apify_client_async_patche async with Actor: await record_child_run('scrape-eu', 'old-run', actor_id=None, task_id='some-task') - run = await Actor.call_task('some-task', run_name='scrape-eu', memory_mbytes=2048) + run = await Actor.call_task('some-task', run_name='scrape-eu', memory_mbytes=2048, logger=None) assert run.id == 'old-run' assert apify_client_async_patcher.calls['task']['start'] == [] @@ -464,7 +493,7 @@ async def test_named_call_task_rejects_name_recorded_for_actor( async with Actor: await record_child_run('scrape-eu', 'old-run') with pytest.raises(ValueError, match='already used for a different Actor, task or input'): - await Actor.call_task('some-task', run_name='scrape-eu') + await Actor.call_task('some-task', run_name='scrape-eu', logger=None) assert apify_client_async_patcher.calls['task']['start'] == [] @@ -478,7 +507,7 @@ async def test_named_runs_forward_max_items_to_start(apify_client_async_patcher: async with Actor: await Actor.start('some-actor', run_name='started', max_items=10) await Actor.call('some-actor', run_name='called', max_items=20, logger=None) - await Actor.call_task('some-task', run_name='task-called', max_items=30) + await Actor.call_task('some-task', run_name='task-called', max_items=30, logger=None) assert [kwargs['max_items'] for _, kwargs in apify_client_async_patcher.calls['actor']['start']] == [10, 20] [(_, task_kwargs)] = apify_client_async_patcher.calls['task']['start'] @@ -838,7 +867,7 @@ async def test_named_call_task_records_abort_with_parent( apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: - await Actor.call_task('some-task', run_name='scrape-eu', abort_with_parent=True) + await Actor.call_task('some-task', run_name='scrape-eu', abort_with_parent=True, logger=None) kvs = await Actor.open_key_value_store() stored = await kvs.get_value(CHILD_RUNS_KEY) @@ -1198,7 +1227,7 @@ async def test_named_run_warns_experimental( async with Actor: method = getattr(Actor, method_name) target = 'some-task' if method_name.endswith('_task') else 'some-actor' - kwargs = {'logger': None} if method_name == 'call' else {} + kwargs = {'logger': None} if method_name in {'call', 'call_task'} else {} with pytest.warns(UserWarning, match='experimental') as warnings: await method(target, run_name='scrape-eu', **kwargs) diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 2d740e4b6..90e1c864f 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -5,8 +5,9 @@ import warnings from datetime import UTC, datetime, timedelta from decimal import Decimal +from types import SimpleNamespace from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, MagicMock, Mock, patch import pytest @@ -68,6 +69,24 @@ def fake_actor_run() -> Run: ) +@pytest.fixture(autouse=True) +def run_waiting(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> SimpleNamespace: + """Make waiting for a run and redirecting its log work without the API, as `Actor.call_task` does both. + + Returns the mocks that stand in for `RunClientAsync.get_streamed_log` and `get_status_message_watcher`. + """ + mocks = SimpleNamespace( + get_streamed_log=Mock(return_value=MagicMock()), + get_status_message_watcher=Mock(return_value=MagicMock()), + ) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=fake_actor_run) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=mocks.get_streamed_log) + apify_client_async_patcher.patch( + 'run', 'get_status_message_watcher', replacement_method=mocks.get_status_message_watcher + ) + return mocks + + async def test_new_client_config_creation(monkeypatch: pytest.MonkeyPatch) -> None: token = 'my-token' monkeypatch.setenv(ApifyEnvVars.TOKEN, token) @@ -118,14 +137,63 @@ async def test_call_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, f async def test_call_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: - apify_client_async_patcher.patch('task', 'call', return_value=fake_actor_run) + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) task_id = 'some-task-id' async with Actor: - await Actor.call_task(task_id) + run = await Actor.call_task(task_id) + + assert run is fake_actor_run + assert len(apify_client_async_patcher.calls['task']['start']) == 1 + assert apify_client_async_patcher.calls['task']['start'][0][0][0].resource_id == task_id + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 + + +async def test_call_actor_task_streams_run_log_by_default( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` redirects the log and the status messages of the run to the default logger.""" + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + await Actor.call_task('some-task-id') - assert len(apify_client_async_patcher.calls['task']['call']) == 1 - assert apify_client_async_patcher.calls['task']['call'][0][0][0].resource_id == task_id + assert run_waiting.get_streamed_log.call_args.kwargs == {'to_logger': None, 'from_start': True} + assert run_waiting.get_status_message_watcher.call_args.kwargs == {'to_logger': None} + run_waiting.get_streamed_log.return_value.__aenter__.assert_awaited_once() + run_waiting.get_status_message_watcher.return_value.__aenter__.assert_awaited_once() + [(args, _)] = apify_client_async_patcher.calls['run']['wait_for_finish'] + assert args[0].resource_id == fake_actor_run.id + + +async def test_call_actor_task_streams_run_log_to_custom_logger( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` redirects the log of the run to the logger it is given.""" + custom_logger = logging.getLogger('custom') + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + await Actor.call_task('some-task-id', logger=custom_logger) + + assert run_waiting.get_streamed_log.call_args.kwargs['to_logger'] is custom_logger + assert run_waiting.get_status_message_watcher.call_args.kwargs['to_logger'] is custom_logger + + +async def test_call_actor_task_without_logger_only_waits( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: + """`Actor.call_task` with `logger=None` waits for the run without redirecting its log or status messages.""" + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + run = await Actor.call_task('some-task-id', wait=timedelta(seconds=5), logger=None) + + assert run is fake_actor_run + run_waiting.get_streamed_log.assert_not_called() + run_waiting.get_status_message_watcher.assert_not_called() + [(_, kwargs)] = apify_client_async_patcher.calls['run']['wait_for_finish'] + assert kwargs == {'wait_duration': timedelta(seconds=5)} async def test_start_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: @@ -160,7 +228,7 @@ async def test_start_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), ], ) async def test_max_items_forwarded_to_client( @@ -186,7 +254,7 @@ async def test_max_items_forwarded_to_client( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) @@ -214,7 +282,7 @@ async def test_max_items_warns_deprecated( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), pytest.param('run', 'resurrect', 'resurrect', id='resurrect'), ], ) @@ -240,7 +308,7 @@ async def test_no_max_items_warning_without_max_items( pytest.param('actor', 'start', 'start', id='start'), pytest.param('actor', 'call', 'call', id='call'), pytest.param('task', 'start', 'start_task', id='start_task'), - pytest.param('task', 'call', 'call_task', id='call_task'), + pytest.param('task', 'start', 'call_task', id='call_task'), ], ) async def test_max_total_charge_usd_forwarded_to_client( @@ -499,7 +567,7 @@ async def listener(_data: object) -> None: pytest.param('actor', 'start', 'start', 'some-actor-id', id='start'), pytest.param('actor', 'call', 'call', 'some-actor-id', id='call'), pytest.param('task', 'start', 'start_task', 'some-task-id', id='start_task'), - pytest.param('task', 'call', 'call_task', 'some-task-id', id='call_task'), + pytest.param('task', 'start', 'call_task', 'some-task-id', id='call_task'), ] @@ -640,7 +708,7 @@ async def test_actor_start_and_call_skipped_when_no_inherited_time_remains( ('client_method', 'actor_method_name'), [ pytest.param('start', 'start_task', id='start_task'), - pytest.param('call', 'call_task', id='call_task'), + pytest.param('start', 'call_task', id='call_task'), ], ) async def test_actor_task_methods_skipped_when_no_inherited_time_remains( From 836eb608bbc327486ca7afe36fc389b5da5454fd Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:41:22 +0100 Subject: [PATCH 2/7] test: make the run waiting fixture async to leak no event loop --- tests/unit/actor/test_actor_helpers.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 90e1c864f..7bf7dcb91 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -70,9 +70,10 @@ def fake_actor_run() -> Run: @pytest.fixture(autouse=True) -def run_waiting(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> SimpleNamespace: +async def run_waiting(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> SimpleNamespace: """Make waiting for a run and redirecting its log work without the API, as `Actor.call_task` does both. + The fixture is async, since the patcher needs the running event loop to build the awaitable return values. Returns the mocks that stand in for `RunClientAsync.get_streamed_log` and `get_status_message_watcher`. """ mocks = SimpleNamespace( From 3cf74a5becdf1717dd60faa2ff056217c00b1209 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:41:54 +0100 Subject: [PATCH 3/7] test: tell the finished task run from the started one --- tests/unit/actor/test_actor_child_runs.py | 4 ++-- tests/unit/actor/test_actor_helpers.py | 14 +++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index af8526eed..4fa1be68c 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -836,7 +836,7 @@ async def test_abort_with_parent_requires_run_name( """`abort_with_parent` without a `run_name` raises before any run is started.""" for resource in ('actor', 'task'): apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) - apify_client_async_patcher.patch(resource, 'call', return_value=make_run('new-run', 'SUCCEEDED')) + apify_client_async_patcher.patch('actor', 'call', return_value=make_run('new-run', 'SUCCEEDED')) async with Actor: with pytest.raises(ValueError, match='requires `run_name`'): @@ -844,7 +844,7 @@ async def test_abort_with_parent_requires_run_name( for resource in ('actor', 'task'): assert apify_client_async_patcher.calls[resource]['start'] == [] - assert apify_client_async_patcher.calls[resource]['call'] == [] + assert apify_client_async_patcher.calls['actor']['call'] == [] async def test_named_start_records_abort_with_parent(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 7bf7dcb91..14d0883f2 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -74,13 +74,15 @@ async def run_waiting(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_ """Make waiting for a run and redirecting its log work without the API, as `Actor.call_task` does both. The fixture is async, since the patcher needs the running event loop to build the awaitable return values. - Returns the mocks that stand in for `RunClientAsync.get_streamed_log` and `get_status_message_watcher`. + Returns the run that the wait ends with, and the mocks that stand in for `RunClientAsync.get_streamed_log` and + `get_status_message_watcher`. """ mocks = SimpleNamespace( + finished_run=fake_actor_run.model_copy(update={'status': 'SUCCEEDED'}), get_streamed_log=Mock(return_value=MagicMock()), get_status_message_watcher=Mock(return_value=MagicMock()), ) - apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=fake_actor_run) + apify_client_async_patcher.patch('run', 'wait_for_finish', return_value=mocks.finished_run) apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=mocks.get_streamed_log) apify_client_async_patcher.patch( 'run', 'get_status_message_watcher', replacement_method=mocks.get_status_message_watcher @@ -137,14 +139,16 @@ async def test_call_actor(apify_client_async_patcher: ApifyClientAsyncPatcher, f assert apify_client_async_patcher.calls['actor']['call'][0][0][0].resource_id == actor_id -async def test_call_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: +async def test_call_actor_task( + apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run, run_waiting: SimpleNamespace +) -> None: apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) task_id = 'some-task-id' async with Actor: run = await Actor.call_task(task_id) - assert run is fake_actor_run + assert run is run_waiting.finished_run assert len(apify_client_async_patcher.calls['task']['start']) == 1 assert apify_client_async_patcher.calls['task']['start'][0][0][0].resource_id == task_id assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 @@ -190,7 +194,7 @@ async def test_call_actor_task_without_logger_only_waits( async with Actor: run = await Actor.call_task('some-task-id', wait=timedelta(seconds=5), logger=None) - assert run is fake_actor_run + assert run is run_waiting.finished_run run_waiting.get_streamed_log.assert_not_called() run_waiting.get_status_message_watcher.assert_not_called() [(_, kwargs)] = apify_client_async_patcher.calls['run']['wait_for_finish'] From e707381704dd8cf0d5f49dc707746c1c0d751ff8 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:42:15 +0100 Subject: [PATCH 4/7] fix: send the start request of `Actor.call_task` without a timeout --- src/apify/_actor.py | 2 ++ tests/unit/actor/test_actor_helpers.py | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index fe53a9c1d..acd8d244b 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1695,6 +1695,8 @@ async def call_task( 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', ) run = await self._wait_for_run(client.run(started_run.id), wait=wait, logger=logger, from_start=True) else: diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 14d0883f2..7c6324aa0 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -149,8 +149,9 @@ async def test_call_actor_task( run = await Actor.call_task(task_id) assert run is run_waiting.finished_run - assert len(apify_client_async_patcher.calls['task']['start']) == 1 - assert apify_client_async_patcher.calls['task']['start'][0][0][0].resource_id == task_id + [(start_args, start_kwargs)] = apify_client_async_patcher.calls['task']['start'] + assert start_args[0].resource_id == task_id + assert start_kwargs['timeout'] == 'no_timeout' assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 From 45604807c877af11bd193e0c95e1b5c643786705 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:42:40 +0100 Subject: [PATCH 5/7] fix: wait for the run without its log when the log redirect fails --- src/apify/_actor.py | 13 +++++++++++-- tests/unit/actor/test_actor_helpers.py | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index acd8d244b..5bd31e11e 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1496,8 +1496,17 @@ async def _wait_for_run( return await run_client.wait_for_finish(wait_duration=wait) to_logger = None if logger == 'default' else logger - status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) - streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) + try: + status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) + streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) + except Exception: + # The run is already started, so a failed redirect must not hide it from the caller. + self.log.warning( + 'Failed to redirect the log of the run, waiting for the run without it', + exc_info=True, + extra={'run_id': run_client.resource_id}, + ) + return await run_client.wait_for_finish(wait_duration=wait) async with status_redirector, streamed_log: return await run_client.wait_for_finish(wait_duration=wait) diff --git a/tests/unit/actor/test_actor_helpers.py b/tests/unit/actor/test_actor_helpers.py index 7c6324aa0..a6d6460de 100644 --- a/tests/unit/actor/test_actor_helpers.py +++ b/tests/unit/actor/test_actor_helpers.py @@ -202,6 +202,24 @@ async def test_call_actor_task_without_logger_only_waits( assert kwargs == {'wait_duration': timedelta(seconds=5)} +async def test_call_actor_task_waits_for_the_run_when_the_log_redirect_fails( + apify_client_async_patcher: ApifyClientAsyncPatcher, + fake_actor_run: Run, + run_waiting: SimpleNamespace, + caplog: pytest.LogCaptureFixture, +) -> None: + """`Actor.call_task` still waits for the started run when the redirect of its log cannot be set up.""" + run_waiting.get_streamed_log.side_effect = RuntimeError('API is down') + apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) + + async with Actor: + run = await Actor.call_task('some-task-id') + + assert run is run_waiting.finished_run + assert len(apify_client_async_patcher.calls['run']['wait_for_finish']) == 1 + assert 'Failed to redirect the log of the run' in caplog.text + + async def test_start_actor_task(apify_client_async_patcher: ApifyClientAsyncPatcher, fake_actor_run: Run) -> None: """`Actor.start_task` starts the task through the client's `task.start` and returns the run.""" apify_client_async_patcher.patch('task', 'start', return_value=fake_actor_run) From 5e0dd1a84a399c9b3e14fc2e4e4b8f86b59590ee Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:43:13 +0100 Subject: [PATCH 6/7] fix: redirect the log of a run once for concurrent named calls --- src/apify/_actor.py | 38 ++++++++++++++--------- tests/unit/actor/test_actor_child_runs.py | 32 +++++++++++++++++++ 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 5bd31e11e..62c9ab3fc 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -183,6 +183,9 @@ def __init__( self._child_run_registry = ChildRunRegistry(self.open_key_value_store) + self._runs_with_redirected_log: set[str | None] = set() + """IDs of the runs whose log a call of this Actor redirects right now.""" + self._internal_listeners = ExitStack() """Removes the listeners the Actor registered on the event manager, when the Actor leaves its context.""" @@ -1492,24 +1495,31 @@ async def _wait_for_run( from_start: bool, ) -> Run | None: """Wait for a run to finish, and redirect its log and status messages to `logger` meanwhile.""" - if not logger: + run_id = run_client.resource_id + # A second redirect of the same run, e.g. from a concurrent call under the same `run_name`, would repeat + # each line of its log. + if not logger or run_id in self._runs_with_redirected_log: return await run_client.wait_for_finish(wait_duration=wait) - to_logger = None if logger == 'default' else logger + self._runs_with_redirected_log.add(run_id) try: - status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) - streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) - except Exception: - # The run is already started, so a failed redirect must not hide it from the caller. - self.log.warning( - 'Failed to redirect the log of the run, waiting for the run without it', - exc_info=True, - extra={'run_id': run_client.resource_id}, - ) - return await run_client.wait_for_finish(wait_duration=wait) + to_logger = None if logger == 'default' else logger + try: + status_redirector = await run_client.get_status_message_watcher(to_logger=to_logger) + streamed_log = await run_client.get_streamed_log(to_logger=to_logger, from_start=from_start) + except Exception: + # The run is already started, so a failed redirect must not hide it from the caller. + self.log.warning( + 'Failed to redirect the log of the run, waiting for the run without it', + exc_info=True, + extra={'run_id': run_id}, + ) + return await run_client.wait_for_finish(wait_duration=wait) - async with status_redirector, streamed_log: - return await run_client.wait_for_finish(wait_duration=wait) + async with status_redirector, streamed_log: + return await run_client.wait_for_finish(wait_duration=wait) + finally: + self._runs_with_redirected_log.discard(run_id) @_ensure_context async def start_task( diff --git a/tests/unit/actor/test_actor_child_runs.py b/tests/unit/actor/test_actor_child_runs.py index 4fa1be68c..ffe876497 100644 --- a/tests/unit/actor/test_actor_child_runs.py +++ b/tests/unit/actor/test_actor_child_runs.py @@ -466,6 +466,38 @@ async def test_named_call_task_streams_run_log( streamed_log.__aenter__.assert_awaited_once() +@pytest.mark.parametrize( + ('method', 'resource'), + [ + pytest.param('call', 'actor', id='call'), + pytest.param('call_task', 'task', id='call task'), + ], +) +async def test_concurrent_named_calls_redirect_the_run_log_once( + apify_client_async_patcher: ApifyClientAsyncPatcher, method: str, resource: str +) -> None: + """Concurrent calls under one name share one run, and only one of them redirects its log.""" + get_streamed_log = Mock(return_value=MagicMock()) + + async def wait_for_finish(*_args: Any, **_kwargs: Any) -> Run: + await asyncio.sleep(0.05) + return make_run('new-run', 'SUCCEEDED') + + apify_client_async_patcher.patch(resource, 'start', return_value=make_run('new-run', 'READY')) + apify_client_async_patcher.patch('run', 'get', return_value=make_run('new-run', 'RUNNING')) + apify_client_async_patcher.patch('run', 'wait_for_finish', replacement_method=wait_for_finish) + apify_client_async_patcher.patch('run', 'get_status_message_watcher', return_value=MagicMock()) + apify_client_async_patcher.patch('run', 'get_streamed_log', replacement_method=get_streamed_log) + + async with Actor: + calls = [getattr(Actor, method)('some-id', run_name='scrape-eu') for _ in range(3)] + runs = await asyncio.gather(*calls) + + assert {run.status for run in runs} == {'SUCCEEDED'} + assert len(apify_client_async_patcher.calls[resource]['start']) == 1 + assert get_streamed_log.call_count == 1 + + async def test_named_call_task_resurrects_recorded_run(apify_client_async_patcher: ApifyClientAsyncPatcher) -> None: """A named task call resurrects an aborted run with its own options.""" apify_client_async_patcher.patch('task', 'start', return_value=make_run('new-run', 'READY')) From ee165886ed8862a3cc2b5c4ce9a49e7d9e1415ba Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Fri, 20 Nov 2026 19:43:59 +0100 Subject: [PATCH 7/7] docs: describe the delay of the log redirect in `Actor.call_task` --- docs/02_concepts/09_logging.mdx | 4 ++-- src/apify/_actor.py | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/02_concepts/09_logging.mdx b/docs/02_concepts/09_logging.mdx index 93399b876..c360fe2a2 100644 --- a/docs/02_concepts/09_logging.mdx +++ b/docs/02_concepts/09_logging.mdx @@ -94,12 +94,12 @@ In some situations, one Actor is going to start one or more other Actors and wai Typical use case for log redirection is to call another Actor using the `Actor.call` method. This method has an optional `logger` argument, which is by default set to the `default` literal. This means that the logs of the called Actor will be automatically redirected to the parent Actor's logs with default formatting and filtering. If you set the `logger` argument to `None`, then no log redirection happens. The third option is to pass your own `Logger` instance with the possibility to define your own formatter, filter, and handler. Below you can see those three possible ways of log redirection when starting another Actor run through `Actor.call`. -The `Actor.call_task` method has the same `logger` argument, with the same default. - {RedirectLog} +The `Actor.call_task` method has the same `logger` argument, with the same default. + Each default redirect logger log entry will have a specific format. After the timestamp, it will contain cyan colored text that will contain the redirect information: the other Actor's name and the run ID. The rest of the log message will be printed in the same manner as the parent Actor's logger is configured. The log redirection can be deep, meaning that if the other Actor also starts another Actor and is redirecting logs from it, then in the top-level Actor, you can see it as well. See the following example screenshot of the Apify log console when one Actor recursively starts itself (there are 2 levels of recursion in the example). diff --git a/src/apify/_actor.py b/src/apify/_actor.py index 62c9ab3fc..143157491 100644 --- a/src/apify/_actor.py +++ b/src/apify/_actor.py @@ -1673,7 +1673,9 @@ async def call_task( wait: The maximum time the server waits for the run to finish. If not provided, waits indefinitely. logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined default logger will be used. Setting `None` will disable any log propagation. Passing custom logger - will redirect logs to the provided logger. + will redirect logs to the provided logger. With a logger, the method returns about 6 seconds after + the run finishes or `wait` runs out, since the redirect waits that long for the last status message + of the run. run_name: Optional name of the child run, unique within this Actor run. A named run is recorded in the default key-value store, so after a migration or resurrection of this Actor the same call reattaches to the recorded run. A `SUCCEEDED` run is returned as is, an `ABORTED` or `TIMED-OUT` one is