Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/02_concepts/09_logging.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ Typical use case for log redirection is to call another Actor using the <ApiLink
{RedirectLog}
</RunnableCodeBlock>

The <ApiLink to="class/Actor#call_task">`Actor.call_task`</ApiLink> 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).
Expand Down
66 changes: 53 additions & 13 deletions src/apify/_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -1477,20 +1480,47 @@ 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."""
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)

self._runs_with_redirected_log.add(run_id)
try:
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)
finally:
self._runs_with_redirected_log.discard(run_id)

@_ensure_context
async def start_task(
self,
Expand Down Expand Up @@ -1608,6 +1638,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,
Expand Down Expand Up @@ -1640,6 +1671,11 @@ 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. 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
Expand Down Expand Up @@ -1670,7 +1706,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,
Expand All @@ -1679,10 +1716,12 @@ async def call_task(
memory_mbytes=memory_mbytes,
run_timeout=self._resolve_run_timeout(timeout),
webhooks=to_client_representations(webhooks),
wait_duration=wait,
# 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:
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,
Expand All @@ -1706,8 +1745,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:
Expand Down
79 changes: 70 additions & 9 deletions tests/unit/actor/test_actor_child_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -430,13 +430,74 @@ 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()


@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'))
Expand All @@ -446,7 +507,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'] == []
Expand All @@ -464,7 +525,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'] == []

Expand All @@ -478,7 +539,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']
Expand Down Expand Up @@ -807,15 +868,15 @@ 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`'):
await getattr(Actor, method)('some-id', abort_with_parent=True)

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:
Expand All @@ -838,7 +899,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)

Expand Down Expand Up @@ -1198,7 +1259,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)

Expand Down
Loading
Loading