From 9a702a26f9f3b5bfbe3bb78458ab9d5ceb33efe1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:29:40 +0000 Subject: [PATCH 01/17] feat: redirect run logs from a given time and resume after the platform closes the stream `RunClient.get_streamed_log()`, `StreamedLog`, and their async counterparts take a `since` datetime and redirect only the log lines logged at that time or later. The `from_start` argument is deprecated in favour of it: `from_start=True` maps to `since=None` and `from_start=False` to `since=datetime.now(tz=UTC)`. It emits a `DeprecationWarning` and will be removed in v4, which the new v4 upgrading guide describes. The platform closes a log stream that has carried no data for several minutes, even when the run is still going (apify/apify-core#26653). A streamed log created by `get_streamed_log()` now checks the run status when its stream ends, reopens the stream if the run has not finished, and skips the replayed lines up to the last redirected one. A stream that broke off with an error gets one more reopen after the run finishes, so the last lines are not lost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- docs/02_concepts/06_logging.mdx | 4 + .../02_concepts/code/06_redirect_run_async.py | 6 +- docs/02_concepts/code/06_redirect_run_sync.py | 6 +- docs/04_upgrading/upgrading_to_v4.mdx | 27 ++ src/apify_client/_resource_clients/run.py | 42 +- src/apify_client/_streamed_log.py | 296 ++++++++++++-- tests/unit/test_logging.py | 377 +++++++++++++++--- 7 files changed, 645 insertions(+), 113 deletions(-) create mode 100644 docs/04_upgrading/upgrading_to_v4.mdx diff --git a/docs/02_concepts/06_logging.mdx b/docs/02_concepts/06_logging.mdx index acc20232..2d41e65f 100644 --- a/docs/02_concepts/06_logging.mdx +++ b/docs/02_concepts/06_logging.mdx @@ -74,3 +74,7 @@ For a run started with `ActorClient.start` + +By default, the whole log of the run is redirected. To redirect only part of it, pass a `datetime` as `since`, and only the lines logged at that time or later are redirected. A naive `datetime` is treated as UTC. The deprecated `from_start` argument still works: `from_start=False` is the same as `since=datetime.now(tz=UTC)`. + +The platform closes a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client checks the run status, reopens the stream if the run hasn't finished, and continues after the last redirected line, so a run that stays quiet for a long time keeps its log redirected. The reopened stream delivers the log from its start, and the client skips the lines it has already redirected. diff --git a/docs/02_concepts/code/06_redirect_run_async.py b/docs/02_concepts/code/06_redirect_run_async.py index 333f733e..d55fce97 100644 --- a/docs/02_concepts/code/06_redirect_run_async.py +++ b/docs/02_concepts/code/06_redirect_run_async.py @@ -1,3 +1,5 @@ +from datetime import UTC, datetime + from apify_client import ApifyClientAsync TOKEN = 'MY-APIFY-TOKEN' @@ -20,8 +22,8 @@ async def main() -> None: actor_run = await actor_client.start() run_client = apify_client.run(actor_run.id) - # With `from_start=False`, only log lines written from now on are redirected. - streamed_log = await run_client.get_streamed_log(from_start=False) + # With `since`, only log lines written at that time or later are redirected. + streamed_log = await run_client.get_streamed_log(since=datetime.now(tz=UTC)) streamed_log.start() # Do other work while the run's log is redirected. await streamed_log.stop() diff --git a/docs/02_concepts/code/06_redirect_run_sync.py b/docs/02_concepts/code/06_redirect_run_sync.py index 4281c5fe..411e2c24 100644 --- a/docs/02_concepts/code/06_redirect_run_sync.py +++ b/docs/02_concepts/code/06_redirect_run_sync.py @@ -1,3 +1,5 @@ +from datetime import UTC, datetime + from apify_client import ApifyClient TOKEN = 'MY-APIFY-TOKEN' @@ -20,8 +22,8 @@ def main() -> None: actor_run = actor_client.start() run_client = apify_client.run(actor_run.id) - # With `from_start=False`, only log lines written from now on are redirected. - streamed_log = run_client.get_streamed_log(from_start=False) + # With `since`, only log lines written at that time or later are redirected. + streamed_log = run_client.get_streamed_log(since=datetime.now(tz=UTC)) streamed_log.start() # Do other work while the run's log is redirected. streamed_log.stop() diff --git a/docs/04_upgrading/upgrading_to_v4.mdx b/docs/04_upgrading/upgrading_to_v4.mdx new file mode 100644 index 00000000..0d1529b3 --- /dev/null +++ b/docs/04_upgrading/upgrading_to_v4.mdx @@ -0,0 +1,27 @@ +--- +id: upgrading-to-v4 +title: Upgrading to v4 +description: Breaking changes and migration guide from v3 to v4. +--- + +import ApiLink from '@theme/ApiLink'; + +This guide lists the breaking changes between Apify Python API Client v3.x and v4.0. + +## `from_start` removed from log redirection + +The `from_start` argument of `RunClient.get_streamed_log()`, `StreamedLog`, and their async counterparts has been removed. Use `since`, which takes a `datetime` and redirects only the log lines logged at that time or later: + +```python +from datetime import UTC, datetime + +# Before +streamed_log = run_client.get_streamed_log(from_start=True) +streamed_log = run_client.get_streamed_log(from_start=False) + +# After +streamed_log = run_client.get_streamed_log() # or since=None +streamed_log = run_client.get_streamed_log(since=datetime.now(tz=UTC)) +``` + +`since` can also start the redirection from any other point in the run's log, for example `since=datetime.now(tz=UTC) - timedelta(minutes=5)` for the last five minutes. A naive `datetime` is treated as UTC. diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index 22c44711..8134f65b 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -4,7 +4,7 @@ import random import string import time -from datetime import timedelta +from datetime import datetime, timedelta from typing import TYPE_CHECKING, Any, Literal from apify_client._docs import docs_group @@ -14,7 +14,7 @@ from apify_client._pagination import DEFAULT_CHUNK_SIZE from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES, ResourceClient, ResourceClientAsync from apify_client._status_message_watcher import StatusMessageWatcher, StatusMessageWatcherAsync -from apify_client._streamed_log import StreamedLog, StreamedLogAsync +from apify_client._streamed_log import StreamedLog, StreamedLogAsync, resolve_since from apify_client._utils.encoding import encode_key_value_store_record_value from apify_client._utils.http import response_to_dict, to_safe_id from apify_client._utils.time import to_seconds @@ -350,23 +350,30 @@ def get_streamed_log( self, to_logger: logging.Logger | None = None, *, - from_start: bool = True, + since: datetime | None = None, + from_start: bool | None = None, timeout: Timeout = 'long', ) -> StreamedLog: """Get `StreamedLog` instance that can be used to redirect logs. - `StreamedLog` can be explicitly started and stopped or used as a context manager. + `StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes + the log stream while the run is still going, for example after the run has logged nothing for several + minutes, the stream is reopened and the redirection resumes after the last redirected message. Args: to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created - from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly - arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant - logs for long-running Actors in stand-by. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for + long-running Actors, such as Server Actors. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. timeout: Timeout for the API HTTP request. Returns: `StreamedLog` instance for redirected logs. """ + # Skips `resolve_since`, this method, and the `WithLogDetailsClient` wrapper around it. + since = resolve_since(since=since, from_start=from_start, stacklevel=3) run_data = self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' @@ -387,7 +394,7 @@ def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLog(log_client=self.log(), to_logger=to_logger, from_start=from_start) + return StreamedLog(log_client=self.log(), to_logger=to_logger, since=since, run_client=self) def charge( self, @@ -943,23 +950,30 @@ async def get_streamed_log( self, to_logger: logging.Logger | None = None, *, - from_start: bool = True, + since: datetime | None = None, + from_start: bool | None = None, timeout: Timeout = 'long', ) -> StreamedLogAsync: """Get `StreamedLog` instance that can be used to redirect logs. - `StreamedLog` can be explicitly started and stopped or used as a context manager. + `StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes + the log stream while the run is still going, for example after the run has logged nothing for several + minutes, the stream is reopened and the redirection resumes after the last redirected message. Args: to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created - from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly - arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant - logs for long-running Actors in stand-by. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for + long-running Actors, such as Server Actors. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. timeout: Timeout for the API HTTP request. Returns: `StreamedLog` instance for redirected logs. """ + # Skips `resolve_since`, this method, and the `WithLogDetailsClient` wrapper around it. + since = resolve_since(since=since, from_start=from_start, stacklevel=3) run_data = await self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' @@ -980,7 +994,7 @@ async def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, from_start=from_start) + return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, since=since, run_client=self) async def charge( self, diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 687a3215..2ec014aa 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -4,17 +4,19 @@ import logging import re import threading +import warnings from asyncio import Task from datetime import UTC, datetime from threading import Thread from typing import TYPE_CHECKING, ClassVar, Self from apify_client._docs import docs_group +from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES if TYPE_CHECKING: from types import TracebackType - from apify_client._resource_clients import LogClient, LogClientAsync + from apify_client._resource_clients import LogClient, LogClientAsync, RunClient, RunClientAsync from apify_client.http_clients import HttpResponse from apify_client.types import Timeout @@ -23,6 +25,34 @@ _LEVEL_PATTERN = re.compile(r'\b(CRITICAL|FATAL|ERROR|WARNING|WARN|INFO|DEBUG)\b') +def _as_utc(value: datetime | None) -> datetime | None: + """Return `value` as an aware datetime, treating a naive one as UTC like the rest of the client does.""" + if value is None or value.tzinfo is not None: + return value + return value.replace(tzinfo=UTC) + + +def resolve_since(*, since: datetime | None, from_start: bool | None, stacklevel: int) -> datetime | None: + """Return the time to redirect the log from, given `since` and the deprecated `from_start` argument. + + A set `from_start` emits a `DeprecationWarning` pointing `stacklevel` frames above the caller of this function. + `from_start=True` means the whole log, `from_start=False` the log from now on. + + Raises: + ValueError: If both `since` and `from_start` are set. + """ + if from_start is None: + return since + warnings.warn( + 'The `from_start` argument is deprecated and will be removed in v4. Use `since` instead.', + DeprecationWarning, + stacklevel=stacklevel + 1, + ) + if since is not None: + raise ValueError('Pass only one of `since` and `from_start`.') + return None if from_start else datetime.now(tz=UTC) + + class StreamedLogBase: """Base class for streaming and buffering chunked Actor run logs.""" @@ -47,18 +77,38 @@ class StreamedLogBase: _empty_stream_max_retry_s: ClassVar[float] = 5 """Upper bound on the pause between reopens of an empty log stream.""" - def __init__(self, to_logger: logging.Logger, *, from_start: bool = True) -> None: + _reconnect_retry_s: ClassVar[float] = 1 + """Pause before reopening a log stream that ended while the run was still going. + + The platform closes a log stream that has carried no data for several minutes, even though the run goes on. Each + reopen that fails before delivering anything doubles the pause up to `_reconnect_max_retry_s`. + """ + + _reconnect_max_retry_s: ClassVar[float] = 30 + """Upper bound on the pause between reopens of a log stream that ended while the run was still going.""" + + def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) -> None: if self._force_propagate: to_logger.propagate = True self._to_logger = to_logger self._stream_buffer = list[bytes]() self._split_marker = re.compile(rb'(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)') - self._relevancy_time_limit: datetime | None = None if from_start else datetime.now(tz=UTC) + self._since = _as_utc(since) self._received_data = False + self._stream_delivered_data = False + # The timestamp of the last redirected message and how many redirected messages carry it. A reopened stream + # replays the log from its start, and these tell where the redirection left off. + self._last_redirected_at: datetime | None = None + self._redirected_at_last_timestamp = 0 + # Where a reopened stream catches up with the redirection: messages before `_resume_after`, and the first + # `_resume_skip_count` messages at it, were already redirected. + self._resume_after: datetime | None = None + self._resume_skip_count = 0 def _process_new_data(self, data: bytes) -> None: if data: self._received_data = True + self._stream_delivered_data = True self._stream_buffer.append(data) if b'\n' in data: self._log_buffer_content(include_last_part=False) @@ -85,13 +135,55 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: for marker, content in zip(message_markers, message_contents, strict=True): decoded_marker = marker.decode('utf-8') decoded_content = content.decode('utf-8') - if self._relevancy_time_limit: - log_time = datetime.fromisoformat(decoded_marker) - if log_time < self._relevancy_time_limit: - # Skip irrelevant logs - continue + log_time = datetime.fromisoformat(decoded_marker) + if self._is_already_redirected(log_time): + continue + if self._since is not None and log_time < self._since: + continue message = decoded_marker + decoded_content self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) + self._remember_redirected(log_time) + + def _is_already_redirected(self, log_time: datetime) -> bool: + """Return whether a message of a reopened stream was redirected before the stream was reopened. + + The position in the log decides, not the timestamp alone: once the reopened stream gets past the last + redirected message, every later message is new, even one with an older timestamp, which a run that migrated + to a host with a clock running behind can log. + """ + if self._resume_after is None: + return False + if log_time < self._resume_after: + return True + if log_time == self._resume_after and self._resume_skip_count > 0: + self._resume_skip_count -= 1 + return True + self._resume_after = None + return False + + def _remember_redirected(self, log_time: datetime) -> None: + if log_time == self._last_redirected_at: + self._redirected_at_last_timestamp += 1 + else: + self._last_redirected_at = log_time + self._redirected_at_last_timestamp = 1 + + def _prepare_reopen(self) -> None: + """Set up skipping the messages a reopened stream replays, and drop the unterminated line of the ended one. + + The reopened stream delivers that line again in full, so redirecting the cut-off part would log it twice. + """ + self._stream_buffer = [] + self._resume_after = self._last_redirected_at + self._resume_skip_count = self._redirected_at_last_timestamp + + def _flush_tail(self) -> None: + """Redirect the unterminated last line, logging a failure instead of raising it.""" + try: + self._log_buffer_content(include_last_part=True) + except Exception: + # A truncated stream leaves an undecodable tail. + self._to_logger.exception('Log redirection stopped due to unexpected error:') def _process_whole_log(self, log: bytes | None) -> None: """Redirect a whole log read in one request, including its last part.""" @@ -124,18 +216,32 @@ class StreamedLog(StreamedLogBase): without a bound `stop` would wait for the next chunk, which on a quiet run may be hours away. """ - def __init__(self, log_client: LogClient, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__( + self, + log_client: LogClient, + *, + to_logger: logging.Logger, + since: datetime | None = None, + from_start: bool | None = None, + run_client: RunClient | None = None, + ) -> None: """Initialize `StreamedLog`. Args: log_client: The log client used to stream raw log data from the Actor run. to_logger: The logger to which the log messages will be forwarded. - from_start: If `True`, all logs from the start of the Actor run will be streamed. If `False`, only newly - arrived logs will be streamed. This can be useful for long-running Actors in stand-by mode where only - recent logs are relevant. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. + run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is + still going is reopened, and the redirection resumes after the last redirected message. """ - super().__init__(to_logger=to_logger, from_start=from_start) + # Skips `resolve_since` and this method, so the warning points at the caller. + since = resolve_since(since=since, from_start=from_start, stacklevel=2) + super().__init__(to_logger=to_logger, since=since) self._log_client = log_client + self._run_client = run_client self._streaming_thread: Thread | None = None self._log_stream: HttpResponse | None = None self._stop_event = threading.Event() @@ -195,11 +301,43 @@ def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s + reconnect_s = self._reconnect_retry_s + reopened_after_finish = False while not self._stop_event.is_set(): - if not self._stream_log_once() or self._received_data: + self._stream_delivered_data = False + broke_off = False + try: + if not self._stream_log_once(): + return + except Exception as exc: + if not self._may_reopen(): + raise + broke_off = True + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + if not self._received_data: + self._stop_event.wait(retry_s) + retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) + continue + if not self._may_reopen(): + # `stop` may have landed after the ended stream kept its unterminated last line. + self._flush_tail() return - self._stop_event.wait(retry_s) - retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) + try: + run_finished = self._is_run_finished() + except Exception: + self._flush_tail() + raise + # A stream that broke off can miss the last messages of a run that finished meanwhile, so it is + # reopened once more to catch up. A stream that ended on its own carried the whole log. + if run_finished and (not broke_off or reopened_after_finish): + self._flush_tail() + return + reopened_after_finish = run_finished + self._prepare_reopen() + if self._stream_delivered_data: + reconnect_s = self._reconnect_retry_s + self._stop_event.wait(reconnect_s) + reconnect_s = min(reconnect_s * 2, self._reconnect_max_retry_s) except Exception as exc: if self._stop_event.is_set(): # `stop` closed the stream out from under the read, so the failure is expected. @@ -228,9 +366,9 @@ def _stream_log_once(self) -> bool: # Published so `stop` can close the response. self._log_stream = log_stream try: - # `stop` may have run before the response existed for it to close. No earlier stream delivered - # anything, and one opened this late would end after its first chunk, so read the whole log in one - # request. + # `stop` may have run before the response existed for it to close. A stream opened this late would + # end after its first chunk, so leave the log to the one-shot read of a session that has not received + # anything yet, or to the streams before this one. if self._stop_event.is_set(): return True for data in log_stream.iter_bytes(): @@ -240,14 +378,25 @@ def _stream_log_once(self) -> bool: finally: self._log_stream = None try: - # Flush the last buffered part even if the read timed out or was stopped. - self._log_buffer_content(include_last_part=True) + # Flush the last buffered part even if the read timed out or was stopped. A stream that may be + # reopened keeps it until that is decided, since the reopened stream delivers it in full. + self._log_buffer_content(include_last_part=not self._may_reopen()) except Exception: # A truncated stream leaves an undecodable tail, which is worth a traceback even while a stop is # in progress. self._to_logger.exception('Log redirection stopped due to unexpected error:') return True + def _may_reopen(self) -> bool: + """Return whether an ended stream may be reopened to resume the redirection.""" + return self._run_client is not None and self._received_data and not self._stop_event.is_set() + + def _is_run_finished(self) -> bool: + if self._run_client is None: + return True + run = self._run_client.get() + return run is None or run.status in _TERMINAL_STATUSES + @docs_group('Other') class StreamedLogAsync(StreamedLogBase): @@ -263,18 +412,32 @@ class StreamedLogAsync(StreamedLogBase): _stop_timeout_s: ClassVar[float] = 1 """Grace period for in-flight log data before the streaming task is cancelled.""" - def __init__(self, log_client: LogClientAsync, *, to_logger: logging.Logger, from_start: bool = True) -> None: + def __init__( + self, + log_client: LogClientAsync, + *, + to_logger: logging.Logger, + since: datetime | None = None, + from_start: bool | None = None, + run_client: RunClientAsync | None = None, + ) -> None: """Initialize `StreamedLogAsync`. Args: log_client: The async log client used to stream raw log data from the Actor run. to_logger: The logger to which the log messages will be forwarded. - from_start: If `True`, all logs from the start of the Actor run will be streamed. If `False`, only newly - arrived logs will be streamed. This can be useful for long-running Actors in stand-by mode where only - recent logs are relevant. + since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC. + If `None`, the whole log is redirected. + from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as + `since=datetime.now(tz=UTC)`. Will be removed in v4. + run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is + still going is reopened, and the redirection resumes after the last redirected message. """ - super().__init__(to_logger=to_logger, from_start=from_start) + # Skips `resolve_since` and this method, so the warning points at the caller. + since = resolve_since(since=since, from_start=from_start, stacklevel=2) + super().__init__(to_logger=to_logger, since=since) self._log_client = log_client + self._run_client = run_client self._streaming_task: Task | None = None def start(self) -> Task: @@ -332,25 +495,45 @@ async def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s + reconnect_s = self._reconnect_retry_s + reopened_after_finish = False while True: - async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: - if not log_stream: + self._stream_delivered_data = False + broke_off = False + try: + if not await self._stream_log_once(): return - try: - async for data in log_stream.aiter_bytes(): - self._process_new_data(data) - finally: - try: - # Flush the last buffered part even if the task is cancelled by `stop()`. - self._log_buffer_content(include_last_part=True) - except Exception: - # A truncated stream leaves an undecodable tail. Keeping the failure here also keeps the - # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. - self._to_logger.exception('Log redirection stopped due to unexpected error:') - if self._received_data: + except Exception as exc: + if not self._may_reopen(): + raise + broke_off = True + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + if not self._received_data: + await asyncio.sleep(retry_s) + retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) + continue + if not self._may_reopen(): + return + try: + run_finished = await self._is_run_finished() + except Exception: + self._flush_tail() + raise + # A stream that broke off can miss the last messages of a run that finished meanwhile, so it is + # reopened once more to catch up. A stream that ended on its own carried the whole log. + if run_finished and (not broke_off or reopened_after_finish): + self._flush_tail() return - await asyncio.sleep(retry_s) - retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) + reopened_after_finish = run_finished + self._prepare_reopen() + if self._stream_delivered_data: + reconnect_s = self._reconnect_retry_s + await asyncio.sleep(reconnect_s) + reconnect_s = min(reconnect_s * 2, self._reconnect_max_retry_s) + except asyncio.CancelledError: + # `stop` cancelled the task, possibly while an ended stream kept its unterminated last line. + self._flush_tail() + raise except Exception as exc: if self._log_client._http_client.is_timeout_error(exc): # noqa: SLF001 # A timeout on the long-lived stream is an expected terminal condition, not an error. @@ -358,3 +541,32 @@ async def _stream_log(self) -> None: else: # Exception in log redirection should not propagate further. self._to_logger.exception('Log redirection stopped due to unexpected error:') + + async def _stream_log_once(self) -> bool: + """Redirect one log stream until it ends. Return `False` when the log does not exist.""" + async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: + if not log_stream: + return False + try: + async for data in log_stream.aiter_bytes(): + self._process_new_data(data) + finally: + try: + # Flush the last buffered part even if the task is cancelled by `stop()`. A stream that may be + # reopened keeps it until that is decided, since the reopened stream delivers it in full. + self._log_buffer_content(include_last_part=not self._may_reopen()) + except Exception: + # A truncated stream leaves an undecodable tail. Keeping the failure here also keeps the + # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. + self._to_logger.exception('Log redirection stopped due to unexpected error:') + return True + + def _may_reopen(self) -> bool: + """Return whether an ended stream may be reopened to resume the redirection.""" + return self._run_client is not None and self._received_data + + async def _is_run_finished(self) -> bool: + if self._run_client is None: + return True + run = await self._run_client.get() + return run is None or run.status in _TERMINAL_STATUSES diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index da7d23b4..b2b65f00 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -10,7 +10,7 @@ from contextlib import asynccontextmanager, nullcontext from datetime import datetime, timedelta from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, Mock import pytest from werkzeug import Request, Response @@ -60,6 +60,8 @@ b'2025-05-13T07:28:14.132Z [apify.redirect-logger runId:4U1oAnKau6jpzjUuA] -> 2025-05-13T07:27:14.132Z ACTOR:...\n', ) _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH = 3 +_REDIRECT_ATTACH_TIME = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') +"""Later than the first `_EXISTING_LOGS_BEFORE_REDIRECT_ATTACH` messages of `_MOCKED_ACTOR_LOGS`.""" # Large enough that a real sleep is clearly detectable against `_FAST_EXIT_THRESHOLD_S`. _PATCHED_FINAL_SLEEP_S = 5 @@ -261,17 +263,21 @@ def reduce_final_timeout_for_status_message_redirector() -> None: @pytest.mark.parametrize( - ('log_from_start', 'expected_log_count'), + ('since', 'expected_log_count'), [ - (True, len(_EXPECTED_MESSAGES_AND_LEVELS)), - (False, len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH), + pytest.param(None, len(_EXPECTED_MESSAGES_AND_LEVELS), id='whole-log'), + pytest.param( + _REDIRECT_ATTACH_TIME, + len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH, + id='since-attach-time', + ), ], ) @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') async def test_redirected_logs_async( *, caplog: LogCaptureFixture, - log_from_start: bool, + since: datetime | None, expected_log_count: int, httpserver: HTTPServer, ) -> None: @@ -281,10 +287,7 @@ async def test_redirected_logs_async( run_client = ApifyClientAsync(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) - with patch('apify_client._streamed_log.datetime') as mocked_datetime: - # Mock `now()` so that it has timestamp bigger than the first 3 logs - mocked_datetime.now.return_value = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') - streamed_log = await run_client.get_streamed_log(from_start=log_from_start) + streamed_log = await run_client.get_streamed_log(since=since) # Set `propagate=True` during the tests, so that caplog can see the logs.. logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' @@ -301,17 +304,21 @@ async def test_redirected_logs_async( @pytest.mark.parametrize( - ('log_from_start', 'expected_log_count'), + ('since', 'expected_log_count'), [ - (True, len(_EXPECTED_MESSAGES_AND_LEVELS)), - (False, len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH), + pytest.param(None, len(_EXPECTED_MESSAGES_AND_LEVELS), id='whole-log'), + pytest.param( + _REDIRECT_ATTACH_TIME, + len(_EXPECTED_MESSAGES_AND_LEVELS) - _EXISTING_LOGS_BEFORE_REDIRECT_ATTACH, + id='since-attach-time', + ), ], ) @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') def test_redirected_logs_sync( *, caplog: LogCaptureFixture, - log_from_start: bool, + since: datetime | None, expected_log_count: int, httpserver: HTTPServer, ) -> None: @@ -321,10 +328,7 @@ def test_redirected_logs_sync( run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) - with patch('apify_client._streamed_log.datetime') as mocked_datetime: - # Mock `now()` so that it has timestamp bigger than the first 3 logs - mocked_datetime.now.return_value = datetime.fromisoformat('2025-05-13T07:24:14.132+00:00') - streamed_log = run_client.get_streamed_log(from_start=log_from_start) + streamed_log = run_client.get_streamed_log(since=since) # Set `propagate=True` during the tests, so that caplog can see the logs.. logger_name = f'apify.{_MOCKED_ACTOR_NAME}-{_MOCKED_RUN_ID}' @@ -1048,8 +1052,8 @@ async def test_async_watcher_aexit_skips_final_sleep_on_exception( _TAIL_SECOND_MESSAGE = '2025-05-13T07:24:13.132Z tail_test trailing partial line' -def _register_run_and_actor_endpoints(httpserver: HTTPServer) -> None: - """Register the minimal run and actor endpoints required by `get_streamed_log`.""" +def _register_run_and_actor_endpoints(httpserver: HTTPServer, *, status: ActorJobStatus = 'RUNNING') -> None: + """Register the minimal run and actor endpoints required by `get_streamed_log`, with the run in `status`.""" httpserver.expect_request(f'/v2/actor-runs/{_MOCKED_RUN_ID}', method='GET').respond_with_json( { 'data': { @@ -1058,7 +1062,7 @@ def _register_run_and_actor_endpoints(httpserver: HTTPServer) -> None: 'userId': 'test_user_id', 'startedAt': '2019-11-30T07:34:24.202Z', 'finishedAt': '2019-12-12T09:30:12.202Z', - 'status': 'RUNNING', + 'status': status, 'statusMessage': 'Running', 'isStatusMessageTerminal': False, 'meta': {'origin': 'WEB'}, @@ -1199,19 +1203,19 @@ def generate_logs() -> Iterator[bytes]: release_server.set() -@pytest.mark.usefixtures('propagate_stream_logs') -def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( - caplog: LogCaptureFixture, - httpserver: HTTPServer, - http_client_class: type[HttpClient], - monkeypatch: pytest.MonkeyPatch, -) -> None: - """The streaming thread ends quietly when either transport times out while reading the log stream.""" - monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) +def _register_timing_out_log_stream(httpserver: HTTPServer, release_server: threading.Event) -> None: + """Serve a log stream that stalls past the client-side stream timeout, and the whole log to any reopened stream.""" + stream_requests: list[Request] = [] - release_server = threading.Event() + def handler(request: Request) -> Response: + stream_requests.append(request) + if len(stream_requests) > 1: + return Response( + b'2025-05-13T07:24:12.588Z ACTOR: still running\n2025-05-13T07:24:13.588Z ACTOR: finished\n', + status=200, + mimetype='application/octet-stream', + ) - def _slow_handler(_request: Request) -> Response: def generate_logs() -> Iterator[bytes]: # Emit one complete line, then keep the connection open (as a running Actor would) past the # client-side stream timeout without sending anything more. @@ -1222,8 +1226,27 @@ def generate_logs() -> Iterator[bytes]: httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' - ).respond_with_handler(_slow_handler) - _register_run_and_actor_endpoints(httpserver) + ).respond_with_handler(handler) + + +def _redirected_log_lines(caplog: LogCaptureFixture) -> list[str]: + """Return the redirected log lines `caplog` captured, without their timestamps.""" + return [record.message.split(' ', 1)[1] for record in caplog.records if record.message.startswith('2025-')] + + +@pytest.mark.usefixtures('propagate_stream_logs') +def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( + caplog: LogCaptureFixture, + httpserver: HTTPServer, + http_client_class: type[HttpClient], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A stream timeout neither leaks nor logs an error, and the reopened stream catches up with the finished run.""" + monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) + + release_server = threading.Event() + _register_timing_out_log_stream(httpserver, release_server) + _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') api_url = httpserver.url_for('/').removesuffix('/') http_client = http_client_class() @@ -1252,8 +1275,8 @@ def generate_logs() -> Iterator[bytes]: # The timeout is expected, so it must be swallowed quietly, not funnelled through the generic error handler. error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'sync thread logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout must still have been redirected. - assert any('ACTOR: still running' in record.message for record in caplog.records) + # The line received before the timeout is redirected once, and the reopened stream adds the rest of the log. + assert _redirected_log_lines(caplog) == ['ACTOR: still running', 'ACTOR: finished'] @pytest.mark.usefixtures('propagate_stream_logs') @@ -1265,7 +1288,7 @@ def test_streamed_log_sync_requests_stream_with_no_timeout( httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' ).respond_with_data(b'2025-05-13T07:24:12.588Z ACTOR: done\n', content_type='application/octet-stream') - _register_run_and_actor_endpoints(httpserver) + _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') api_url = httpserver.url_for('/').removesuffix('/') run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) @@ -1299,23 +1322,12 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( http_client_async_class: type[HttpClientAsync], monkeypatch: pytest.MonkeyPatch, ) -> None: - """The async streaming task treats either transport's stream timeout as an expected terminal condition.""" + """A stream timeout neither raises nor logs an error, and the reopened stream catches up with the finished run.""" monkeypatch.setattr(StreamedLogAsync, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() - - def _slow_handler(_request: Request) -> Response: - def generate_logs() -> Iterator[bytes]: - # Emit one complete line, then keep the connection open past the client-side stream timeout. - yield b'2025-05-13T07:24:12.588Z ACTOR: still running\n' - release_server.wait(timeout=30) - - return Response(response=generate_logs(), status=200, mimetype='application/octet-stream') - - httpserver.expect_request( - f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' - ).respond_with_handler(_slow_handler) - _register_run_and_actor_endpoints(httpserver) + _register_timing_out_log_stream(httpserver, release_server) + _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') api_url = httpserver.url_for('/').removesuffix('/') http_client = http_client_async_class() @@ -1340,8 +1352,8 @@ def generate_logs() -> Iterator[bytes]: assert task.exception() is None, f'async streaming task raised on stream timeout: {task.exception()!r}' error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'async task logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout must still have been redirected. - assert any('ACTOR: still running' in record.message for record in caplog.records) + # The line received before the timeout is redirected once, and the reopened stream adds the rest of the log. + assert _redirected_log_lines(caplog) == ['ACTOR: still running', 'ACTOR: finished'] _POLL_FAILURE_FINAL_SLEEP_S = 2 @@ -1503,7 +1515,8 @@ def generate_logs() -> Iterator[bytes]: httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' ).respond_with_handler(_silent_handler) - _register_run_and_actor_endpoints(httpserver) + # A finished run, so the stream that ends once the server is released is not reopened. + _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') api_url = httpserver.url_for('/').removesuffix('/') run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) @@ -2014,6 +2027,264 @@ async def test_streamed_log_async_missing_log_is_neither_reopened_nor_read() -> log_client.get_as_bytes.assert_not_called() +@pytest.mark.parametrize( + ('from_start', 'expected_since'), + [ + pytest.param(True, None, id='from-start'), + pytest.param(False, _REDIRECT_ATTACH_TIME, id='from-now'), + ], +) +def test_streamed_log_from_start_is_deprecated_alias_of_since( + *, from_start: bool, expected_since: datetime | None, monkeypatch: pytest.MonkeyPatch +) -> None: + """`from_start` warns that it is deprecated, and maps to the whole log or to the log from now on.""" + mocked_datetime = Mock(wraps=datetime) + mocked_datetime.now.return_value = _REDIRECT_ATTACH_TIME + monkeypatch.setattr('apify_client._streamed_log.datetime', mocked_datetime) + + with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), from_start=from_start) + + assert streamed_log._since == expected_since + # The warning points at the code that passed the argument. + assert warning_records[0].filename == __file__ + + +def test_streamed_log_rejects_both_since_and_from_start() -> None: + """Passing both `since` and the deprecated `from_start` is an error.""" + with ( + pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated'), + pytest.raises(ValueError, match='Pass only one of'), + ): + StreamedLog( + log_client=Mock(), to_logger=logging.getLogger('test'), since=_REDIRECT_ATTACH_TIME, from_start=False + ) + + +def test_streamed_log_treats_naive_since_as_utc() -> None: + """A naive `since` is read as UTC, like the log timestamps.""" + naive_since = _REDIRECT_ATTACH_TIME.replace(tzinfo=None) + + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), since=naive_since) + + assert streamed_log._since == _REDIRECT_ATTACH_TIME + + +def test_get_streamed_log_from_start_warning_points_at_caller(httpserver: HTTPServer) -> None: + """The deprecation warning of `get_streamed_log(from_start=...)` points at the code that called it.""" + _register_run_and_actor_endpoints(httpserver) + api_url = httpserver.url_for('/').removesuffix('/') + run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) + + with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: + run_client.get_streamed_log(from_start=False) + + assert warning_records[0].filename == __file__ + + +_LOG_BEFORE_DROP = ( + b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' + b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' + b'2025-05-13T07:24:13.000Z ACTOR: cut o' +) +"""What a log stream delivers before the platform closes it: two messages with the same timestamp, then a cut-off +message.""" + +_LOG_AFTER_DROP = ( + b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' + b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' + b'2025-05-13T07:24:12.588Z ACTOR: line 3 at the same millisecond\n' + b'2025-05-13T07:24:13.000Z ACTOR: cut off before\n' + b'2025-05-13T07:34:13.000Z ACTOR: logged after a long silence\n' +) +"""What the reopened stream delivers: the whole log from its start, with the messages logged meanwhile.""" + +_LINES_AFTER_RESUME = [ + 'ACTOR: line 1', + 'ACTOR: line 2', + 'ACTOR: line 3 at the same millisecond', + 'ACTOR: cut off before', + 'ACTOR: logged after a long silence', +] + + +def _run_with_status(status: ActorJobStatus) -> Mock: + return Mock(status=status) + + +def _sync_streams(*chunk_lists: list[bytes] | Exception) -> list[nullcontext]: + """Return the log streams a mocked `LogClient.stream` opens, one per argument. + + An exception argument makes that stream deliver `_LOG_BEFORE_DROP` and then raise it. + """ + streams = [] + for chunk_list in chunk_lists: + log_stream = Mock() + if isinstance(chunk_list, Exception): + error = chunk_list + + def failing_iter(error: Exception = error) -> Iterator[bytes]: + yield _LOG_BEFORE_DROP + raise error + + log_stream.iter_bytes.side_effect = failing_iter + else: + log_stream.iter_bytes.return_value = chunk_list + streams.append(nullcontext(log_stream)) + return streams + + +def _async_streams(*chunk_lists: list[bytes] | Exception) -> list[nullcontext]: + """Return the log streams a mocked `LogClientAsync.stream` opens, one per argument. + + An exception argument makes that stream deliver `_LOG_BEFORE_DROP` and then raise it. + """ + streams = [] + for chunk_list in chunk_lists: + log_stream = Mock() + if isinstance(chunk_list, Exception): + error = chunk_list + + async def failing_aiter(error: Exception = error) -> AsyncIterator[bytes]: + yield _LOG_BEFORE_DROP + raise error + + log_stream.aiter_bytes.side_effect = failing_aiter + else: + log_stream.aiter_bytes.side_effect = lambda chunk_list=chunk_list: chunks(*chunk_list) + streams.append(nullcontext(log_stream)) + return streams + + +def test_streamed_log_sync_resumes_after_stream_closed_while_run_goes_on( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" + monkeypatch.setattr(StreamedLog, '_reconnect_retry_s', 0) + log_client = Mock() + log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) + run_client = Mock() + run_client.get.side_effect = [_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')] + logger = logging.getLogger('apify_client.tests.resume_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 2 + + +async def test_streamed_log_async_resumes_after_stream_closed_while_run_goes_on( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" + monkeypatch.setattr(StreamedLogAsync, '_reconnect_retry_s', 0) + log_client = Mock() + log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) + run_client = Mock() + run_client.get = AsyncMock(side_effect=[_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')]) + logger = logging.getLogger('apify_client.tests.resume_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 2 + + +def test_streamed_log_sync_catches_up_once_after_stream_broke_off_and_run_finished( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" + monkeypatch.setattr(StreamedLog, '_reconnect_retry_s', 0) + log_client = Mock() + log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) + run_client = Mock() + run_client.get.return_value = _run_with_status('SUCCEEDED') + logger = logging.getLogger('apify_client.tests.catch_up_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 2 + + +async def test_streamed_log_async_catches_up_once_after_stream_broke_off_and_run_finished( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" + monkeypatch.setattr(StreamedLogAsync, '_reconnect_retry_s', 0) + log_client = Mock() + log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) + run_client = Mock() + run_client.get = AsyncMock(return_value=_run_with_status('SUCCEEDED')) + logger = logging.getLogger('apify_client.tests.catch_up_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 2 + + +def test_streamed_log_sync_does_not_reopen_stream_of_finished_run(caplog: LogCaptureFixture) -> None: + """A stream that ends on its own after the run finished is not reopened, and its last line is redirected.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP]) + run_client = Mock() + run_client.get.return_value = _run_with_status('SUCCEEDED') + logger = logging.getLogger('apify_client.tests.finished_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_of_finished_run(caplog: LogCaptureFixture) -> None: + """A stream that ends on its own after the run finished is not reopened, and its last line is redirected.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP]) + run_client = Mock() + run_client.get = AsyncMock(return_value=_run_with_status('SUCCEEDED')) + logger = logging.getLogger('apify_client.tests.finished_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + log_client.stream.assert_called_once() + + +def test_streamed_log_sync_backs_off_between_failing_reopens(monkeypatch: pytest.MonkeyPatch) -> None: + """The pause before reopening a stream doubles while reopened streams fail before delivering anything.""" + log_client = Mock() + log_client.stream.side_effect = [ + *_sync_streams([_LOG_BEFORE_DROP]), + *[ConnectionRefusedError('Simulated failure')] * 6, + *_sync_streams([_LOG_AFTER_DROP]), + ] + run_client = Mock() + run_client.get.side_effect = [_run_with_status('RUNNING')] * 7 + [_run_with_status('SUCCEEDED')] + streamed_log = StreamedLog( + log_client=log_client, to_logger=logging.getLogger('apify_client.tests.reopen_backoff'), run_client=run_client + ) + wait = Mock(return_value=False) + monkeypatch.setattr(streamed_log._stop_event, 'wait', wait) + + streamed_log._stream_log() + + assert [call.args[0] for call in wait.call_args_list] == [1, 2, 4, 8, 16, 30, 30] + + def test_logger_once_logs_the_first_call(caplog: LogCaptureFixture) -> None: """Test the first call with a given key is logged.""" logger = logging.getLogger('apify_client.tests.log_once_first') From 80e1492ece9ae7df1eebda3be037685aa3ffa496 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:39:04 +0000 Subject: [PATCH 02/17] refactor: drop stacklevel handling from the `from_start` deprecation warning Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- src/apify_client/_resource_clients/run.py | 6 ++---- src/apify_client/_streamed_log.py | 14 ++++++-------- tests/unit/test_logging.py | 16 +--------------- 3 files changed, 9 insertions(+), 27 deletions(-) diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index 8134f65b..caae8a1b 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -372,8 +372,7 @@ def get_streamed_log( Returns: `StreamedLog` instance for redirected logs. """ - # Skips `resolve_since`, this method, and the `WithLogDetailsClient` wrapper around it. - since = resolve_since(since=since, from_start=from_start, stacklevel=3) + since = resolve_since(since=since, from_start=from_start) run_data = self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' @@ -972,8 +971,7 @@ async def get_streamed_log( Returns: `StreamedLog` instance for redirected logs. """ - # Skips `resolve_since`, this method, and the `WithLogDetailsClient` wrapper around it. - since = resolve_since(since=since, from_start=from_start, stacklevel=3) + since = resolve_since(since=since, from_start=from_start) run_data = await self.get(timeout=timeout) run_id = f'runId:{run_data.id}' if run_data and run_data.id else '' diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 2ec014aa..2b3bc2de 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -32,11 +32,11 @@ def _as_utc(value: datetime | None) -> datetime | None: return value.replace(tzinfo=UTC) -def resolve_since(*, since: datetime | None, from_start: bool | None, stacklevel: int) -> datetime | None: +def resolve_since(*, since: datetime | None, from_start: bool | None) -> datetime | None: """Return the time to redirect the log from, given `since` and the deprecated `from_start` argument. - A set `from_start` emits a `DeprecationWarning` pointing `stacklevel` frames above the caller of this function. - `from_start=True` means the whole log, `from_start=False` the log from now on. + A set `from_start` emits a `DeprecationWarning`. `from_start=True` means the whole log, `from_start=False` the log + from now on. Raises: ValueError: If both `since` and `from_start` are set. @@ -46,7 +46,7 @@ def resolve_since(*, since: datetime | None, from_start: bool | None, stacklevel warnings.warn( 'The `from_start` argument is deprecated and will be removed in v4. Use `since` instead.', DeprecationWarning, - stacklevel=stacklevel + 1, + stacklevel=2, ) if since is not None: raise ValueError('Pass only one of `since` and `from_start`.') @@ -237,8 +237,7 @@ def __init__( run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is still going is reopened, and the redirection resumes after the last redirected message. """ - # Skips `resolve_since` and this method, so the warning points at the caller. - since = resolve_since(since=since, from_start=from_start, stacklevel=2) + since = resolve_since(since=since, from_start=from_start) super().__init__(to_logger=to_logger, since=since) self._log_client = log_client self._run_client = run_client @@ -433,8 +432,7 @@ def __init__( run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is still going is reopened, and the redirection resumes after the last redirected message. """ - # Skips `resolve_since` and this method, so the warning points at the caller. - since = resolve_since(since=since, from_start=from_start, stacklevel=2) + since = resolve_since(since=since, from_start=from_start) super().__init__(to_logger=to_logger, since=since) self._log_client = log_client self._run_client = run_client diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index b2b65f00..8483e6cf 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2042,12 +2042,10 @@ def test_streamed_log_from_start_is_deprecated_alias_of_since( mocked_datetime.now.return_value = _REDIRECT_ATTACH_TIME monkeypatch.setattr('apify_client._streamed_log.datetime', mocked_datetime) - with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: + with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated'): streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), from_start=from_start) assert streamed_log._since == expected_since - # The warning points at the code that passed the argument. - assert warning_records[0].filename == __file__ def test_streamed_log_rejects_both_since_and_from_start() -> None: @@ -2070,18 +2068,6 @@ def test_streamed_log_treats_naive_since_as_utc() -> None: assert streamed_log._since == _REDIRECT_ATTACH_TIME -def test_get_streamed_log_from_start_warning_points_at_caller(httpserver: HTTPServer) -> None: - """The deprecation warning of `get_streamed_log(from_start=...)` points at the code that called it.""" - _register_run_and_actor_endpoints(httpserver) - api_url = httpserver.url_for('/').removesuffix('/') - run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) - - with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: - run_client.get_streamed_log(from_start=False) - - assert warning_records[0].filename == __file__ - - _LOG_BEFORE_DROP = ( b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' From bdfe0e822cbbab79327e23160a3f2fb51f2d6046 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:48:13 +0000 Subject: [PATCH 03/17] feat: expose `StreamedLog.last_redirected_at` and resume reopened streams from it `StreamedLog` and `StreamedLogAsync` get a read-only `last_redirected_at` property with the timestamp of the last redirected line, so a redirection can be continued in another process, for example after the redirecting Actor reboots, by passing it plus one millisecond as `since`. A stream reopened after the platform closes it uses the same rule: it redirects only lines logged after `last_redirected_at`, which replaces the tracking of how many lines share the last timestamp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- docs/02_concepts/06_logging.mdx | 19 +++++- .../code/06_redirect_resume_async.py | 28 +++++++++ .../code/06_redirect_resume_sync.py | 28 +++++++++ src/apify_client/_streamed_log.py | 63 ++++++++----------- tests/unit/test_logging.py | 46 +++++++++++++- 5 files changed, 143 insertions(+), 41 deletions(-) create mode 100644 docs/02_concepts/code/06_redirect_resume_async.py create mode 100644 docs/02_concepts/code/06_redirect_resume_sync.py diff --git a/docs/02_concepts/06_logging.mdx b/docs/02_concepts/06_logging.mdx index 2d41e65f..5c6c1c83 100644 --- a/docs/02_concepts/06_logging.mdx +++ b/docs/02_concepts/06_logging.mdx @@ -14,6 +14,8 @@ import RedirectCallAsyncExample from '!!raw-loader!./code/06_redirect_call_async import RedirectCallSyncExample from '!!raw-loader!./code/06_redirect_call_sync.py'; import RedirectRunAsyncExample from '!!raw-loader!./code/06_redirect_run_async.py'; import RedirectRunSyncExample from '!!raw-loader!./code/06_redirect_run_sync.py'; +import RedirectResumeAsyncExample from '!!raw-loader!./code/06_redirect_resume_async.py'; +import RedirectResumeSyncExample from '!!raw-loader!./code/06_redirect_resume_sync.py'; import ApiLink from '@theme/ApiLink'; @@ -77,4 +79,19 @@ For a run started with `ActorClient.start` By default, the whole log of the run is redirected. To redirect only part of it, pass a `datetime` as `since`, and only the lines logged at that time or later are redirected. A naive `datetime` is treated as UTC. The deprecated `from_start` argument still works: `from_start=False` is the same as `since=datetime.now(tz=UTC)`. -The platform closes a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client checks the run status, reopens the stream if the run hasn't finished, and continues after the last redirected line, so a run that stays quiet for a long time keeps its log redirected. The reopened stream delivers the log from its start, and the client skips the lines it has already redirected. +The platform closes a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client checks the run status and, if the run hasn't finished, reopens the stream. It then redirects only the lines logged after `StreamedLog.last_redirected_at`, the timestamp of the last redirected line. The reopened stream delivers the log from its start, and the client skips everything up to that point. + +The same property lets you continue the redirection in another process, for example after the Actor that redirects the log reboots. Save `last_redirected_at` before the reboot, and afterwards pass it plus one millisecond as `since`. Log timestamps have millisecond precision, so this skips the last redirected line. It would also skip another line logged in that same millisecond and not yet redirected, which is rare. + + + + + {RedirectResumeAsyncExample} + + + + + {RedirectResumeSyncExample} + + + diff --git a/docs/02_concepts/code/06_redirect_resume_async.py b/docs/02_concepts/code/06_redirect_resume_async.py new file mode 100644 index 00000000..ecc175da --- /dev/null +++ b/docs/02_concepts/code/06_redirect_resume_async.py @@ -0,0 +1,28 @@ +from datetime import datetime, timedelta + +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' +RECORD_KEY = 'LOG_REDIRECTED_UNTIL' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + run_client = apify_client.run('MY-RUN-ID') + store_client = apify_client.key_value_store('MY-STORE-ID') + + # After a reboot, continue after the last line redirected before it. + record = await store_client.get_record(RECORD_KEY) + since = None + if record: + since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1) + + streamed_log = await run_client.get_streamed_log(since=since) + async with streamed_log: + await run_client.wait_for_finish() + + # Before a reboot, save how far the redirection got. Here it is saved once the + # run finishes; save it on your own reboot or migration signal instead. + if streamed_log.last_redirected_at: + redirected_until = streamed_log.last_redirected_at.isoformat() + await store_client.set_record(RECORD_KEY, redirected_until) diff --git a/docs/02_concepts/code/06_redirect_resume_sync.py b/docs/02_concepts/code/06_redirect_resume_sync.py new file mode 100644 index 00000000..ef34ef48 --- /dev/null +++ b/docs/02_concepts/code/06_redirect_resume_sync.py @@ -0,0 +1,28 @@ +from datetime import datetime, timedelta + +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' +RECORD_KEY = 'LOG_REDIRECTED_UNTIL' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + run_client = apify_client.run('MY-RUN-ID') + store_client = apify_client.key_value_store('MY-STORE-ID') + + # After a reboot, continue after the last line redirected before it. + record = store_client.get_record(RECORD_KEY) + since = None + if record: + since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1) + + streamed_log = run_client.get_streamed_log(since=since) + with streamed_log: + run_client.wait_for_finish() + + # Before a reboot, save how far the redirection got. Here it is saved once the + # run finishes; save it on your own reboot or migration signal instead. + if streamed_log.last_redirected_at: + redirected_until = streamed_log.last_redirected_at.isoformat() + store_client.set_record(RECORD_KEY, redirected_until) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 2b3bc2de..b1f5c7f9 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -6,7 +6,7 @@ import threading import warnings from asyncio import Task -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from threading import Thread from typing import TYPE_CHECKING, ClassVar, Self @@ -96,14 +96,7 @@ def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) self._since = _as_utc(since) self._received_data = False self._stream_delivered_data = False - # The timestamp of the last redirected message and how many redirected messages carry it. A reopened stream - # replays the log from its start, and these tell where the redirection left off. self._last_redirected_at: datetime | None = None - self._redirected_at_last_timestamp = 0 - # Where a reopened stream catches up with the redirection: messages before `_resume_after`, and the first - # `_resume_skip_count` messages at it, were already redirected. - self._resume_after: datetime | None = None - self._resume_skip_count = 0 def _process_new_data(self, data: bytes) -> None: if data: @@ -136,46 +129,22 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: decoded_marker = marker.decode('utf-8') decoded_content = content.decode('utf-8') log_time = datetime.fromisoformat(decoded_marker) - if self._is_already_redirected(log_time): - continue if self._since is not None and log_time < self._since: continue message = decoded_marker + decoded_content self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) - self._remember_redirected(log_time) - - def _is_already_redirected(self, log_time: datetime) -> bool: - """Return whether a message of a reopened stream was redirected before the stream was reopened. - - The position in the log decides, not the timestamp alone: once the reopened stream gets past the last - redirected message, every later message is new, even one with an older timestamp, which a run that migrated - to a host with a clock running behind can log. - """ - if self._resume_after is None: - return False - if log_time < self._resume_after: - return True - if log_time == self._resume_after and self._resume_skip_count > 0: - self._resume_skip_count -= 1 - return True - self._resume_after = None - return False - - def _remember_redirected(self, log_time: datetime) -> None: - if log_time == self._last_redirected_at: - self._redirected_at_last_timestamp += 1 - else: self._last_redirected_at = log_time - self._redirected_at_last_timestamp = 1 def _prepare_reopen(self) -> None: - """Set up skipping the messages a reopened stream replays, and drop the unterminated line of the ended one. + """Make the reopened stream redirect only the messages after the last redirected one. - The reopened stream delivers that line again in full, so redirecting the cut-off part would log it twice. + The reopened stream replays the log from its start. Log timestamps have millisecond precision, so new messages + start one millisecond after `_last_redirected_at`. The unterminated line of the ended stream is dropped, since + the reopened stream delivers it in full. """ self._stream_buffer = [] - self._resume_after = self._last_redirected_at - self._resume_skip_count = self._redirected_at_last_timestamp + if self._last_redirected_at is not None: + self._since = self._last_redirected_at + timedelta(milliseconds=1) def _flush_tail(self) -> None: """Redirect the unterminated last line, logging a failure instead of raising it.""" @@ -245,6 +214,15 @@ def __init__( self._log_stream: HttpResponse | None = None self._stop_event = threading.Event() + @property + def last_redirected_at(self) -> datetime | None: + """The timestamp of the last redirected log message, or `None` if nothing has been redirected yet. + + To continue the redirection later, for example after the Actor that redirects the log reboots, save it and + pass it plus one millisecond as `since` to `RunClient.get_streamed_log`. + """ + return self._last_redirected_at + def start(self) -> Thread: """Start the streaming thread. @@ -438,6 +416,15 @@ def __init__( self._run_client = run_client self._streaming_task: Task | None = None + @property + def last_redirected_at(self) -> datetime | None: + """The timestamp of the last redirected log message, or `None` if nothing has been redirected yet. + + To continue the redirection later, for example after the Actor that redirects the log reboots, save it and + pass it plus one millisecond as `since` to `RunClient.get_streamed_log`. + """ + return self._last_redirected_at + def start(self) -> Task: """Start the streaming task. diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 8483e6cf..05d46569 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2079,7 +2079,6 @@ def test_streamed_log_treats_naive_since_as_utc() -> None: _LOG_AFTER_DROP = ( b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' - b'2025-05-13T07:24:12.588Z ACTOR: line 3 at the same millisecond\n' b'2025-05-13T07:24:13.000Z ACTOR: cut off before\n' b'2025-05-13T07:34:13.000Z ACTOR: logged after a long silence\n' ) @@ -2088,11 +2087,12 @@ def test_streamed_log_treats_naive_since_as_utc() -> None: _LINES_AFTER_RESUME = [ 'ACTOR: line 1', 'ACTOR: line 2', - 'ACTOR: line 3 at the same millisecond', 'ACTOR: cut off before', 'ACTOR: logged after a long silence', ] +_LAST_LINE_TIME = datetime.fromisoformat('2025-05-13T07:34:13.000+00:00') + def _run_with_status(status: ActorJobStatus) -> Mock: return Mock(status=status) @@ -2158,6 +2158,7 @@ def test_streamed_log_sync_resumes_after_stream_closed_while_run_goes_on( streamed_log._stream_log() assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME assert log_client.stream.call_count == 2 @@ -2177,6 +2178,7 @@ async def test_streamed_log_async_resumes_after_stream_closed_while_run_goes_on( await streamed_log._stream_log() assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME assert log_client.stream.call_count == 2 @@ -2196,6 +2198,7 @@ def test_streamed_log_sync_catches_up_once_after_stream_broke_off_and_run_finish streamed_log._stream_log() assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME assert log_client.stream.call_count == 2 @@ -2215,6 +2218,7 @@ async def test_streamed_log_async_catches_up_once_after_stream_broke_off_and_run await streamed_log._stream_log() assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert streamed_log.last_redirected_at == _LAST_LINE_TIME assert log_client.stream.call_count == 2 @@ -2250,6 +2254,44 @@ async def test_streamed_log_async_does_not_reopen_stream_of_finished_run(caplog: log_client.stream.assert_called_once() +def test_streamed_log_last_redirected_at_is_none_before_any_message() -> None: + """`last_redirected_at` is `None` until a message is redirected.""" + streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test')) + + assert streamed_log.last_redirected_at is None + + +def test_streamed_log_last_redirected_at_ignores_skipped_messages() -> None: + """Messages skipped for being older than `since` do not move `last_redirected_at`.""" + log_stream = Mock() + log_stream.iter_bytes.return_value = [_LOG_AFTER_DROP] + log_client = Mock() + log_client.stream.return_value = nullcontext(log_stream) + streamed_log = StreamedLog( + log_client=log_client, to_logger=logging.getLogger('test'), since=_LAST_LINE_TIME + timedelta(seconds=1) + ) + + streamed_log._stream_log() + + assert streamed_log.last_redirected_at is None + + +def test_streamed_log_resumes_from_saved_last_redirected_at(caplog: LogCaptureFixture) -> None: + """A new streamed log started from a saved `last_redirected_at` plus one millisecond redirects only newer lines.""" + log_stream = Mock() + log_stream.iter_bytes.return_value = [_LOG_AFTER_DROP] + log_client = Mock() + log_client.stream.return_value = nullcontext(log_stream) + saved = datetime.fromisoformat('2025-05-13T07:24:12.588+00:00') + logger = logging.getLogger('apify_client.tests.resume_saved') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger, since=saved + timedelta(milliseconds=1)) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: cut off before', 'ACTOR: logged after a long silence'] + + def test_streamed_log_sync_backs_off_between_failing_reopens(monkeypatch: pytest.MonkeyPatch) -> None: """The pause before reopening a stream doubles while reopened streams fail before delivering anything.""" log_client = Mock() From ef37604b64a2908c7ef46c6ea235c836137b23f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:53:16 +0000 Subject: [PATCH 04/17] test: e2e test of resuming log redirection after the redirecting Actor reboots The test builds two Actors: one that logs numbered lines, and one that runs a wheel of the client from this checkout. The second one redirects the first one's log, saves `last_redirected_at` to its key-value store, reboots, and resumes with `since`. The test checks that every line was redirected exactly once, with some lines before the reboot and some after it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- .../test_log_redirection_reboot.py | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 tests/integration/test_log_redirection_reboot.py diff --git a/tests/integration/test_log_redirection_reboot.py b/tests/integration/test_log_redirection_reboot.py new file mode 100644 index 00000000..49d9a926 --- /dev/null +++ b/tests/integration/test_log_redirection_reboot.py @@ -0,0 +1,149 @@ +"""End-to-end test of resuming log redirection after the redirecting Actor reboots.""" + +from __future__ import annotations + +import base64 +import re +import subprocess +from datetime import timedelta +from pathlib import Path + +from .._utils import create_built_actor, get_api_url, get_random_resource_name +from apify_client import ApifyClient +from apify_client._models import Run + +REPO_ROOT = Path(__file__).resolve().parents[2] +TARGET_LINE_COUNT = 60 +REBOOT_MARKER = 'REDIRECTOR: rebooting' + +TARGET_SOURCE_FILES = [ + { + 'name': 'Dockerfile', + 'format': 'TEXT', + 'content': 'FROM apify/actor-node:26\nCOPY . ./\nCMD ["node", "main.mjs"]\n', + }, + { + 'name': 'main.mjs', + 'format': 'TEXT', + 'content': f""" +for (let index = 0; index < {TARGET_LINE_COUNT}; index++) {{ + console.log(`TARGET-LINE-${{String(index).padStart(3, '0')}}`); + await new Promise((resolve) => setTimeout(resolve, 1000)); +}} +""", + }, +] +"""Source of an Actor that logs `TARGET_LINE_COUNT` numbered lines, one per second.""" + +REDIRECTOR_MAIN = f""" +import os +import time +from datetime import datetime, timedelta + +from apify_client import ApifyClient + +client = ApifyClient(os.environ['APIFY_TOKEN'], api_url=os.environ['APIFY_API_BASE_URL']) +store = client.key_value_store(os.environ['ACTOR_DEFAULT_KEY_VALUE_STORE_ID']) + +state_record = store.get_record('STATE') +if state_record is None: + target_actor_id = store.get_record('INPUT')['value']['targetActorId'] + target_run = client.actor(target_actor_id).start() + state = {{'targetRunId': target_run.id, 'redirectedUntil': None}} +else: + state = state_record['value'] + +run_client = client.run(state['targetRunId']) +since = None +if state['redirectedUntil']: + since = datetime.fromisoformat(state['redirectedUntil']) + timedelta(milliseconds=1) +streamed_log = run_client.get_streamed_log(since=since) + +if state_record is not None: + # After the reboot: redirect the rest of the log. The stream of the finished run ends on its own, so let it, + # instead of stopping it while it may still deliver the last lines. + streaming_thread = streamed_log.start() + run_client.wait_for_finish() + streaming_thread.join(timeout=120) + streamed_log.stop() +else: + # Before the reboot: redirect a part of the log, save how far it got, and reboot. + streamed_log.start() + deadline = time.monotonic() + 300 + while streamed_log.last_redirected_at is None and time.monotonic() < deadline: + time.sleep(1) + time.sleep(15) + streamed_log.stop() + state['redirectedUntil'] = streamed_log.last_redirected_at.isoformat() + store.set_record('STATE', state) + print('{REBOOT_MARKER}', flush=True) + client.run(os.environ['ACTOR_RUN_ID']).reboot() + # The reboot replaces this container. + time.sleep(600) +""" +"""Source of an Actor that redirects the log of a target Actor run, reboots midway, and resumes the redirection +from the `last_redirected_at` it saved in its key-value store.""" + + +def build_client_wheel(out_dir: Path) -> Path: + """Build a wheel of the client in this checkout, so the redirecting Actor runs the code under test.""" + subprocess.run( # noqa: S603 + ['uv', 'build', '--wheel', '--out-dir', str(out_dir)], # noqa: S607 + check=True, + capture_output=True, + cwd=REPO_ROOT, + ) + return next(out_dir.glob('apify_client-*.whl')) + + +def get_redirector_source_files(wheel: Path) -> list[dict[str, str]]: + return [ + { + 'name': 'Dockerfile', + 'format': 'TEXT', + 'content': ( + 'FROM apify/actor-python:3.13\n' + 'COPY . ./\n' + f'RUN pip install --no-cache-dir ./{wheel.name}\n' + 'CMD ["python", "-u", "main.py"]\n' + ), + }, + {'name': 'main.py', 'format': 'TEXT', 'content': REDIRECTOR_MAIN}, + {'name': wheel.name, 'format': 'BASE64', 'content': base64.b64encode(wheel.read_bytes()).decode()}, + ] + + +def test_streamed_log_resumes_after_redirecting_actor_reboots(api_token: str, tmp_path: Path) -> None: + """Every line of the target run is redirected exactly once, across a reboot of the redirecting Actor.""" + client = ApifyClient(api_token, api_url=get_api_url()) + wheel = build_client_wheel(tmp_path) + + with ( + create_built_actor(client, get_random_resource_name('target'), TARGET_SOURCE_FILES) as target_actor_id, + # Full permissions, so the run token can start the target Actor and read its log. + create_built_actor( + client, + get_random_resource_name('redirector'), + get_redirector_source_files(wheel), + actor_permission_level='FULL_PERMISSIONS', + ) as redirector_actor_id, + ): + redirector_run = client.actor(redirector_actor_id).call( + run_input={'targetActorId': target_actor_id}, + memory_mbytes=256, + run_timeout=timedelta(minutes=10), + logger=None, + ) + assert isinstance(redirector_run, Run) + redirector_log = client.run(redirector_run.id).log().get() + assert redirector_run.status == 'SUCCEEDED', redirector_log + assert redirector_log is not None + + assert redirector_log.count(REBOOT_MARKER) == 1, redirector_log + before_reboot, after_reboot = redirector_log.split(REBOOT_MARKER) + redirected_lines = re.findall(r'TARGET-LINE-\d{3}', redirector_log) + expected_lines = [f'TARGET-LINE-{index:03d}' for index in range(TARGET_LINE_COUNT)] + assert redirected_lines == expected_lines, redirector_log + # The reboot happened midway, so both runs of the redirecting Actor redirected a part of the log. + assert 'TARGET-LINE-' in before_reboot + assert 'TARGET-LINE-' in after_reboot From acb39aa992f5360cd86aee21fdc03fb651b87170 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:22:38 +0000 Subject: [PATCH 05/17] test: remove the one-off reboot e2e test of log redirection Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- .../test_log_redirection_reboot.py | 149 ------------------ 1 file changed, 149 deletions(-) delete mode 100644 tests/integration/test_log_redirection_reboot.py diff --git a/tests/integration/test_log_redirection_reboot.py b/tests/integration/test_log_redirection_reboot.py deleted file mode 100644 index 49d9a926..00000000 --- a/tests/integration/test_log_redirection_reboot.py +++ /dev/null @@ -1,149 +0,0 @@ -"""End-to-end test of resuming log redirection after the redirecting Actor reboots.""" - -from __future__ import annotations - -import base64 -import re -import subprocess -from datetime import timedelta -from pathlib import Path - -from .._utils import create_built_actor, get_api_url, get_random_resource_name -from apify_client import ApifyClient -from apify_client._models import Run - -REPO_ROOT = Path(__file__).resolve().parents[2] -TARGET_LINE_COUNT = 60 -REBOOT_MARKER = 'REDIRECTOR: rebooting' - -TARGET_SOURCE_FILES = [ - { - 'name': 'Dockerfile', - 'format': 'TEXT', - 'content': 'FROM apify/actor-node:26\nCOPY . ./\nCMD ["node", "main.mjs"]\n', - }, - { - 'name': 'main.mjs', - 'format': 'TEXT', - 'content': f""" -for (let index = 0; index < {TARGET_LINE_COUNT}; index++) {{ - console.log(`TARGET-LINE-${{String(index).padStart(3, '0')}}`); - await new Promise((resolve) => setTimeout(resolve, 1000)); -}} -""", - }, -] -"""Source of an Actor that logs `TARGET_LINE_COUNT` numbered lines, one per second.""" - -REDIRECTOR_MAIN = f""" -import os -import time -from datetime import datetime, timedelta - -from apify_client import ApifyClient - -client = ApifyClient(os.environ['APIFY_TOKEN'], api_url=os.environ['APIFY_API_BASE_URL']) -store = client.key_value_store(os.environ['ACTOR_DEFAULT_KEY_VALUE_STORE_ID']) - -state_record = store.get_record('STATE') -if state_record is None: - target_actor_id = store.get_record('INPUT')['value']['targetActorId'] - target_run = client.actor(target_actor_id).start() - state = {{'targetRunId': target_run.id, 'redirectedUntil': None}} -else: - state = state_record['value'] - -run_client = client.run(state['targetRunId']) -since = None -if state['redirectedUntil']: - since = datetime.fromisoformat(state['redirectedUntil']) + timedelta(milliseconds=1) -streamed_log = run_client.get_streamed_log(since=since) - -if state_record is not None: - # After the reboot: redirect the rest of the log. The stream of the finished run ends on its own, so let it, - # instead of stopping it while it may still deliver the last lines. - streaming_thread = streamed_log.start() - run_client.wait_for_finish() - streaming_thread.join(timeout=120) - streamed_log.stop() -else: - # Before the reboot: redirect a part of the log, save how far it got, and reboot. - streamed_log.start() - deadline = time.monotonic() + 300 - while streamed_log.last_redirected_at is None and time.monotonic() < deadline: - time.sleep(1) - time.sleep(15) - streamed_log.stop() - state['redirectedUntil'] = streamed_log.last_redirected_at.isoformat() - store.set_record('STATE', state) - print('{REBOOT_MARKER}', flush=True) - client.run(os.environ['ACTOR_RUN_ID']).reboot() - # The reboot replaces this container. - time.sleep(600) -""" -"""Source of an Actor that redirects the log of a target Actor run, reboots midway, and resumes the redirection -from the `last_redirected_at` it saved in its key-value store.""" - - -def build_client_wheel(out_dir: Path) -> Path: - """Build a wheel of the client in this checkout, so the redirecting Actor runs the code under test.""" - subprocess.run( # noqa: S603 - ['uv', 'build', '--wheel', '--out-dir', str(out_dir)], # noqa: S607 - check=True, - capture_output=True, - cwd=REPO_ROOT, - ) - return next(out_dir.glob('apify_client-*.whl')) - - -def get_redirector_source_files(wheel: Path) -> list[dict[str, str]]: - return [ - { - 'name': 'Dockerfile', - 'format': 'TEXT', - 'content': ( - 'FROM apify/actor-python:3.13\n' - 'COPY . ./\n' - f'RUN pip install --no-cache-dir ./{wheel.name}\n' - 'CMD ["python", "-u", "main.py"]\n' - ), - }, - {'name': 'main.py', 'format': 'TEXT', 'content': REDIRECTOR_MAIN}, - {'name': wheel.name, 'format': 'BASE64', 'content': base64.b64encode(wheel.read_bytes()).decode()}, - ] - - -def test_streamed_log_resumes_after_redirecting_actor_reboots(api_token: str, tmp_path: Path) -> None: - """Every line of the target run is redirected exactly once, across a reboot of the redirecting Actor.""" - client = ApifyClient(api_token, api_url=get_api_url()) - wheel = build_client_wheel(tmp_path) - - with ( - create_built_actor(client, get_random_resource_name('target'), TARGET_SOURCE_FILES) as target_actor_id, - # Full permissions, so the run token can start the target Actor and read its log. - create_built_actor( - client, - get_random_resource_name('redirector'), - get_redirector_source_files(wheel), - actor_permission_level='FULL_PERMISSIONS', - ) as redirector_actor_id, - ): - redirector_run = client.actor(redirector_actor_id).call( - run_input={'targetActorId': target_actor_id}, - memory_mbytes=256, - run_timeout=timedelta(minutes=10), - logger=None, - ) - assert isinstance(redirector_run, Run) - redirector_log = client.run(redirector_run.id).log().get() - assert redirector_run.status == 'SUCCEEDED', redirector_log - assert redirector_log is not None - - assert redirector_log.count(REBOOT_MARKER) == 1, redirector_log - before_reboot, after_reboot = redirector_log.split(REBOOT_MARKER) - redirected_lines = re.findall(r'TARGET-LINE-\d{3}', redirector_log) - expected_lines = [f'TARGET-LINE-{index:03d}' for index in range(TARGET_LINE_COUNT)] - assert redirected_lines == expected_lines, redirector_log - # The reboot happened midway, so both runs of the redirecting Actor redirected a part of the log. - assert 'TARGET-LINE-' in before_reboot - assert 'TARGET-LINE-' in after_reboot From 79aaea6788f0ea29f8fced214b4a71ca9a234a03 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:24:39 +0000 Subject: [PATCH 06/17] test: e2e test of log redirection from a run that stays silent for six minutes The Actor under test logs a counter for 30 seconds, counts silently until 390 seconds, which is longer than the platform keeps an idle log stream open, and then logs the counter again. The test checks that `ActorClient.call` redirects every logged line exactly once and that the log stream was reopened. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- .../test_log_redirection_silent_run.py | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 tests/integration/test_log_redirection_silent_run.py diff --git a/tests/integration/test_log_redirection_silent_run.py b/tests/integration/test_log_redirection_silent_run.py new file mode 100644 index 00000000..17d5e509 --- /dev/null +++ b/tests/integration/test_log_redirection_silent_run.py @@ -0,0 +1,70 @@ +"""End-to-end test of log redirection from a run that stays silent for longer than the platform keeps a stream open.""" + +from __future__ import annotations + +import logging +import re +from datetime import timedelta +from typing import TYPE_CHECKING +from unittest.mock import create_autospec + +from .._utils import create_built_actor, get_api_url, get_random_resource_name +from apify_client import ApifyClient +from apify_client._models import Run +from apify_client._resource_clients import LogClient + +if TYPE_CHECKING: + import pytest + from _pytest.logging import LogCaptureFixture + +LOGGED_UNTIL_S = 30 +SILENT_UNTIL_S = 390 +COUNT_UNTIL_S = 420 + +SILENT_ACTOR_SOURCE_FILES = [ + { + 'name': 'Dockerfile', + 'format': 'TEXT', + 'content': 'FROM apify/actor-node:26\nCOPY . ./\nCMD ["node", "main.mjs"]\n', + }, + { + 'name': 'main.mjs', + 'format': 'TEXT', + 'content': f""" +for (let second = 0; second < {COUNT_UNTIL_S}; second++) {{ + if (second < {LOGGED_UNTIL_S} || second >= {SILENT_UNTIL_S}) {{ + console.log(`COUNTER-${{String(second).padStart(3, '0')}}`); + }} + await new Promise((resolve) => setTimeout(resolve, 1000)); +}} +await new Promise((resolve) => setTimeout(resolve, 5000)); +""", + }, +] +"""Source of an Actor that counts seconds: it logs the count for the first `LOGGED_UNTIL_S` seconds, counts silently +until `SILENT_UNTIL_S`, and then logs the count again until `COUNT_UNTIL_S`.""" + + +def test_streamed_log_resumes_after_platform_closes_silent_stream( + api_token: str, caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """Every line of a run that stays silent for six minutes is redirected exactly once, over a reopened stream.""" + client = ApifyClient(api_token, api_url=get_api_url()) + stream = create_autospec(LogClient.stream, side_effect=LogClient.stream) + monkeypatch.setattr(LogClient, 'stream', stream) + logger = logging.getLogger('apify_client.tests.silent_run') + + with ( + create_built_actor(client, get_random_resource_name('silent'), SILENT_ACTOR_SOURCE_FILES) as actor_id, + caplog.at_level(logging.INFO, logger=logger.name), + ): + run = client.actor(actor_id).call(memory_mbytes=256, run_timeout=timedelta(minutes=10), logger=logger) + assert isinstance(run, Run) + assert run.status == 'SUCCEEDED' + + redirected = '\n'.join(record.message for record in caplog.records if record.name == logger.name) + counted_seconds = [*range(LOGGED_UNTIL_S), *range(SILENT_UNTIL_S, COUNT_UNTIL_S)] + expected_lines = [f'COUNTER-{second:03d}' for second in counted_seconds] + assert re.findall(r'COUNTER-\d{3}', redirected) == expected_lines, redirected + # The platform closed the stream during the silence, so the lines after it came over a reopened stream. + assert stream.call_count >= 2, f'The log stream was opened {stream.call_count} time(s).' From d49cecf51859a65dc31c6be425100f16ee451c8d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:33:11 +0000 Subject: [PATCH 07/17] test: run the silent-run log redirection e2e test in a redirecting Actor A redirector Actor running a wheel of the client from this checkout calls the silent counting Actor with the default logger, so the redirected lines land in the redirector's own log. The test checks that log for every counter line, exactly once, and for the number of times the log stream was opened. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- .../test_log_redirection_silent_run.py | 106 ++++++++++++++---- 1 file changed, 83 insertions(+), 23 deletions(-) diff --git a/tests/integration/test_log_redirection_silent_run.py b/tests/integration/test_log_redirection_silent_run.py index 17d5e509..10078a25 100644 --- a/tests/integration/test_log_redirection_silent_run.py +++ b/tests/integration/test_log_redirection_silent_run.py @@ -1,21 +1,18 @@ -"""End-to-end test of log redirection from a run that stays silent for longer than the platform keeps a stream open.""" +"""End-to-end test of an Actor redirecting the log of another Actor that stays silent for six minutes.""" from __future__ import annotations -import logging +import base64 import re +import subprocess from datetime import timedelta -from typing import TYPE_CHECKING -from unittest.mock import create_autospec +from pathlib import Path from .._utils import create_built_actor, get_api_url, get_random_resource_name from apify_client import ApifyClient from apify_client._models import Run -from apify_client._resource_clients import LogClient -if TYPE_CHECKING: - import pytest - from _pytest.logging import LogCaptureFixture +REPO_ROOT = Path(__file__).resolve().parents[2] LOGGED_UNTIL_S = 30 SILENT_UNTIL_S = 390 @@ -44,27 +41,90 @@ """Source of an Actor that counts seconds: it logs the count for the first `LOGGED_UNTIL_S` seconds, counts silently until `SILENT_UNTIL_S`, and then logs the count again until `COUNT_UNTIL_S`.""" +REDIRECTOR_MAIN = """ +import os +from unittest.mock import create_autospec + +from apify_client import ApifyClient +from apify_client._resource_clients import LogClient + +# Counts how many times the log stream is opened, to show the platform closed it during the silence. +stream = create_autospec(LogClient.stream, side_effect=LogClient.stream) +LogClient.stream = stream + +client = ApifyClient(os.environ['APIFY_TOKEN'], api_url=os.environ['APIFY_API_BASE_URL']) +store = client.key_value_store(os.environ['ACTOR_DEFAULT_KEY_VALUE_STORE_ID']) +target_actor_id = store.get_record('INPUT')['value']['targetActorId'] + +# The default logger redirects the target run's log into this run's log. +run = client.actor(target_actor_id).call(memory_mbytes=256) + +print(f'REDIRECTOR: target run finished as {run.status}', flush=True) +print(f'REDIRECTOR: log stream opened {stream.call_count} times', flush=True) +""" +"""Source of an Actor that calls the target Actor and redirects its log into its own log.""" + + +def build_client_wheel(out_dir: Path) -> Path: + """Build a wheel of the client in this checkout, so the redirecting Actor runs the code under test.""" + subprocess.run( # noqa: S603 + ['uv', 'build', '--wheel', '--out-dir', str(out_dir)], # noqa: S607 + check=True, + capture_output=True, + cwd=REPO_ROOT, + ) + return next(out_dir.glob('apify_client-*.whl')) + + +def get_redirector_source_files(wheel: Path) -> list[dict[str, str]]: + return [ + { + 'name': 'Dockerfile', + 'format': 'TEXT', + 'content': ( + 'FROM apify/actor-python:3.13\n' + 'COPY . ./\n' + f'RUN pip install --no-cache-dir ./{wheel.name}\n' + 'CMD ["python", "-u", "main.py"]\n' + ), + }, + {'name': 'main.py', 'format': 'TEXT', 'content': REDIRECTOR_MAIN}, + {'name': wheel.name, 'format': 'BASE64', 'content': base64.b64encode(wheel.read_bytes()).decode()}, + ] + -def test_streamed_log_resumes_after_platform_closes_silent_stream( - api_token: str, caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """Every line of a run that stays silent for six minutes is redirected exactly once, over a reopened stream.""" +def test_actor_redirects_log_of_actor_silent_for_six_minutes(api_token: str, tmp_path: Path) -> None: + """An Actor redirects every line of another Actor's run exactly once, although that run stays silent for six + minutes and the platform closes the log stream meanwhile.""" client = ApifyClient(api_token, api_url=get_api_url()) - stream = create_autospec(LogClient.stream, side_effect=LogClient.stream) - monkeypatch.setattr(LogClient, 'stream', stream) - logger = logging.getLogger('apify_client.tests.silent_run') + wheel = build_client_wheel(tmp_path) with ( - create_built_actor(client, get_random_resource_name('silent'), SILENT_ACTOR_SOURCE_FILES) as actor_id, - caplog.at_level(logging.INFO, logger=logger.name), + create_built_actor(client, get_random_resource_name('silent'), SILENT_ACTOR_SOURCE_FILES) as target_actor_id, + # Full permissions, so the run token can start the target Actor and read its log. + create_built_actor( + client, + get_random_resource_name('redirector'), + get_redirector_source_files(wheel), + actor_permission_level='FULL_PERMISSIONS', + ) as redirector_actor_id, ): - run = client.actor(actor_id).call(memory_mbytes=256, run_timeout=timedelta(minutes=10), logger=logger) - assert isinstance(run, Run) - assert run.status == 'SUCCEEDED' + redirector_run = client.actor(redirector_actor_id).call( + run_input={'targetActorId': target_actor_id}, + memory_mbytes=256, + run_timeout=timedelta(minutes=15), + logger=None, + ) + assert isinstance(redirector_run, Run) + redirector_log = client.run(redirector_run.id).log().get() + assert redirector_log is not None + assert redirector_run.status == 'SUCCEEDED', redirector_log - redirected = '\n'.join(record.message for record in caplog.records if record.name == logger.name) + assert 'REDIRECTOR: target run finished as SUCCEEDED' in redirector_log, redirector_log counted_seconds = [*range(LOGGED_UNTIL_S), *range(SILENT_UNTIL_S, COUNT_UNTIL_S)] expected_lines = [f'COUNTER-{second:03d}' for second in counted_seconds] - assert re.findall(r'COUNTER-\d{3}', redirected) == expected_lines, redirected + assert re.findall(r'COUNTER-\d{3}', redirector_log) == expected_lines, redirector_log # The platform closed the stream during the silence, so the lines after it came over a reopened stream. - assert stream.call_count >= 2, f'The log stream was opened {stream.call_count} time(s).' + stream_opens = re.search(r'REDIRECTOR: log stream opened (\d+) times', redirector_log) + assert stream_opens is not None, redirector_log + assert int(stream_opens[1]) >= 2, redirector_log From 504002516c7fb5eb8b7a9c89668492797950528b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:42:00 +0000 Subject: [PATCH 08/17] test: give both Actor runs of the silent-run e2e test enough time Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- tests/integration/test_log_redirection_silent_run.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_log_redirection_silent_run.py b/tests/integration/test_log_redirection_silent_run.py index 10078a25..05e18b47 100644 --- a/tests/integration/test_log_redirection_silent_run.py +++ b/tests/integration/test_log_redirection_silent_run.py @@ -43,6 +43,7 @@ REDIRECTOR_MAIN = """ import os +from datetime import timedelta from unittest.mock import create_autospec from apify_client import ApifyClient @@ -57,7 +58,7 @@ target_actor_id = store.get_record('INPUT')['value']['targetActorId'] # The default logger redirects the target run's log into this run's log. -run = client.actor(target_actor_id).call(memory_mbytes=256) +run = client.actor(target_actor_id).call(memory_mbytes=256, run_timeout=timedelta(minutes=15)) print(f'REDIRECTOR: target run finished as {run.status}', flush=True) print(f'REDIRECTOR: log stream opened {stream.call_count} times', flush=True) @@ -112,7 +113,7 @@ def test_actor_redirects_log_of_actor_silent_for_six_minutes(api_token: str, tmp redirector_run = client.actor(redirector_actor_id).call( run_input={'targetActorId': target_actor_id}, memory_mbytes=256, - run_timeout=timedelta(minutes=15), + run_timeout=timedelta(minutes=20), logger=None, ) assert isinstance(redirector_run, Run) From 95e0fe751a91917fc1f874e98167e088d152075d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:52:16 +0000 Subject: [PATCH 09/17] test: remove the one-off silent-run e2e test of log redirection Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- .../test_log_redirection_silent_run.py | 131 ------------------ 1 file changed, 131 deletions(-) delete mode 100644 tests/integration/test_log_redirection_silent_run.py diff --git a/tests/integration/test_log_redirection_silent_run.py b/tests/integration/test_log_redirection_silent_run.py deleted file mode 100644 index 05e18b47..00000000 --- a/tests/integration/test_log_redirection_silent_run.py +++ /dev/null @@ -1,131 +0,0 @@ -"""End-to-end test of an Actor redirecting the log of another Actor that stays silent for six minutes.""" - -from __future__ import annotations - -import base64 -import re -import subprocess -from datetime import timedelta -from pathlib import Path - -from .._utils import create_built_actor, get_api_url, get_random_resource_name -from apify_client import ApifyClient -from apify_client._models import Run - -REPO_ROOT = Path(__file__).resolve().parents[2] - -LOGGED_UNTIL_S = 30 -SILENT_UNTIL_S = 390 -COUNT_UNTIL_S = 420 - -SILENT_ACTOR_SOURCE_FILES = [ - { - 'name': 'Dockerfile', - 'format': 'TEXT', - 'content': 'FROM apify/actor-node:26\nCOPY . ./\nCMD ["node", "main.mjs"]\n', - }, - { - 'name': 'main.mjs', - 'format': 'TEXT', - 'content': f""" -for (let second = 0; second < {COUNT_UNTIL_S}; second++) {{ - if (second < {LOGGED_UNTIL_S} || second >= {SILENT_UNTIL_S}) {{ - console.log(`COUNTER-${{String(second).padStart(3, '0')}}`); - }} - await new Promise((resolve) => setTimeout(resolve, 1000)); -}} -await new Promise((resolve) => setTimeout(resolve, 5000)); -""", - }, -] -"""Source of an Actor that counts seconds: it logs the count for the first `LOGGED_UNTIL_S` seconds, counts silently -until `SILENT_UNTIL_S`, and then logs the count again until `COUNT_UNTIL_S`.""" - -REDIRECTOR_MAIN = """ -import os -from datetime import timedelta -from unittest.mock import create_autospec - -from apify_client import ApifyClient -from apify_client._resource_clients import LogClient - -# Counts how many times the log stream is opened, to show the platform closed it during the silence. -stream = create_autospec(LogClient.stream, side_effect=LogClient.stream) -LogClient.stream = stream - -client = ApifyClient(os.environ['APIFY_TOKEN'], api_url=os.environ['APIFY_API_BASE_URL']) -store = client.key_value_store(os.environ['ACTOR_DEFAULT_KEY_VALUE_STORE_ID']) -target_actor_id = store.get_record('INPUT')['value']['targetActorId'] - -# The default logger redirects the target run's log into this run's log. -run = client.actor(target_actor_id).call(memory_mbytes=256, run_timeout=timedelta(minutes=15)) - -print(f'REDIRECTOR: target run finished as {run.status}', flush=True) -print(f'REDIRECTOR: log stream opened {stream.call_count} times', flush=True) -""" -"""Source of an Actor that calls the target Actor and redirects its log into its own log.""" - - -def build_client_wheel(out_dir: Path) -> Path: - """Build a wheel of the client in this checkout, so the redirecting Actor runs the code under test.""" - subprocess.run( # noqa: S603 - ['uv', 'build', '--wheel', '--out-dir', str(out_dir)], # noqa: S607 - check=True, - capture_output=True, - cwd=REPO_ROOT, - ) - return next(out_dir.glob('apify_client-*.whl')) - - -def get_redirector_source_files(wheel: Path) -> list[dict[str, str]]: - return [ - { - 'name': 'Dockerfile', - 'format': 'TEXT', - 'content': ( - 'FROM apify/actor-python:3.13\n' - 'COPY . ./\n' - f'RUN pip install --no-cache-dir ./{wheel.name}\n' - 'CMD ["python", "-u", "main.py"]\n' - ), - }, - {'name': 'main.py', 'format': 'TEXT', 'content': REDIRECTOR_MAIN}, - {'name': wheel.name, 'format': 'BASE64', 'content': base64.b64encode(wheel.read_bytes()).decode()}, - ] - - -def test_actor_redirects_log_of_actor_silent_for_six_minutes(api_token: str, tmp_path: Path) -> None: - """An Actor redirects every line of another Actor's run exactly once, although that run stays silent for six - minutes and the platform closes the log stream meanwhile.""" - client = ApifyClient(api_token, api_url=get_api_url()) - wheel = build_client_wheel(tmp_path) - - with ( - create_built_actor(client, get_random_resource_name('silent'), SILENT_ACTOR_SOURCE_FILES) as target_actor_id, - # Full permissions, so the run token can start the target Actor and read its log. - create_built_actor( - client, - get_random_resource_name('redirector'), - get_redirector_source_files(wheel), - actor_permission_level='FULL_PERMISSIONS', - ) as redirector_actor_id, - ): - redirector_run = client.actor(redirector_actor_id).call( - run_input={'targetActorId': target_actor_id}, - memory_mbytes=256, - run_timeout=timedelta(minutes=20), - logger=None, - ) - assert isinstance(redirector_run, Run) - redirector_log = client.run(redirector_run.id).log().get() - assert redirector_log is not None - assert redirector_run.status == 'SUCCEEDED', redirector_log - - assert 'REDIRECTOR: target run finished as SUCCEEDED' in redirector_log, redirector_log - counted_seconds = [*range(LOGGED_UNTIL_S), *range(SILENT_UNTIL_S, COUNT_UNTIL_S)] - expected_lines = [f'COUNTER-{second:03d}' for second in counted_seconds] - assert re.findall(r'COUNTER-\d{3}', redirector_log) == expected_lines, redirector_log - # The platform closed the stream during the silence, so the lines after it came over a reopened stream. - stream_opens = re.search(r'REDIRECTOR: log stream opened (\d+) times', redirector_log) - assert stream_opens is not None, redirector_log - assert int(stream_opens[1]) >= 2, redirector_log From 7cbea014da260f0671f8c9b8b8bd7f7437adcb46 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:57:00 +0000 Subject: [PATCH 10/17] refactor: reopen a closed log stream after a fixed pause instead of a backoff Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- src/apify_client/_streamed_log.py | 24 ++++-------------------- tests/unit/test_logging.py | 29 ++++------------------------- 2 files changed, 8 insertions(+), 45 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index b1f5c7f9..b41a7b05 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -77,16 +77,12 @@ class StreamedLogBase: _empty_stream_max_retry_s: ClassVar[float] = 5 """Upper bound on the pause between reopens of an empty log stream.""" - _reconnect_retry_s: ClassVar[float] = 1 + _reopen_pause_s: ClassVar[float] = 1 """Pause before reopening a log stream that ended while the run was still going. - The platform closes a log stream that has carried no data for several minutes, even though the run goes on. Each - reopen that fails before delivering anything doubles the pause up to `_reconnect_max_retry_s`. + The platform closes a log stream that has carried no data for several minutes, even though the run goes on. """ - _reconnect_max_retry_s: ClassVar[float] = 30 - """Upper bound on the pause between reopens of a log stream that ended while the run was still going.""" - def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) -> None: if self._force_propagate: to_logger.propagate = True @@ -95,13 +91,11 @@ def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) self._split_marker = re.compile(rb'(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)') self._since = _as_utc(since) self._received_data = False - self._stream_delivered_data = False self._last_redirected_at: datetime | None = None def _process_new_data(self, data: bytes) -> None: if data: self._received_data = True - self._stream_delivered_data = True self._stream_buffer.append(data) if b'\n' in data: self._log_buffer_content(include_last_part=False) @@ -278,10 +272,8 @@ def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - reconnect_s = self._reconnect_retry_s reopened_after_finish = False while not self._stop_event.is_set(): - self._stream_delivered_data = False broke_off = False try: if not self._stream_log_once(): @@ -311,10 +303,7 @@ def _stream_log(self) -> None: return reopened_after_finish = run_finished self._prepare_reopen() - if self._stream_delivered_data: - reconnect_s = self._reconnect_retry_s - self._stop_event.wait(reconnect_s) - reconnect_s = min(reconnect_s * 2, self._reconnect_max_retry_s) + self._stop_event.wait(self._reopen_pause_s) except Exception as exc: if self._stop_event.is_set(): # `stop` closed the stream out from under the read, so the failure is expected. @@ -480,10 +469,8 @@ async def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - reconnect_s = self._reconnect_retry_s reopened_after_finish = False while True: - self._stream_delivered_data = False broke_off = False try: if not await self._stream_log_once(): @@ -511,10 +498,7 @@ async def _stream_log(self) -> None: return reopened_after_finish = run_finished self._prepare_reopen() - if self._stream_delivered_data: - reconnect_s = self._reconnect_retry_s - await asyncio.sleep(reconnect_s) - reconnect_s = min(reconnect_s * 2, self._reconnect_max_retry_s) + await asyncio.sleep(self._reopen_pause_s) except asyncio.CancelledError: # `stop` cancelled the task, possibly while an ended stream kept its unterminated last line. self._flush_tail() diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 05d46569..53eea814 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2146,7 +2146,7 @@ def test_streamed_log_sync_resumes_after_stream_closed_while_run_goes_on( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" - monkeypatch.setattr(StreamedLog, '_reconnect_retry_s', 0) + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) run_client = Mock() @@ -2166,7 +2166,7 @@ async def test_streamed_log_async_resumes_after_stream_closed_while_run_goes_on( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" - monkeypatch.setattr(StreamedLogAsync, '_reconnect_retry_s', 0) + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) run_client = Mock() @@ -2186,7 +2186,7 @@ def test_streamed_log_sync_catches_up_once_after_stream_broke_off_and_run_finish caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" - monkeypatch.setattr(StreamedLog, '_reconnect_retry_s', 0) + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) run_client = Mock() @@ -2206,7 +2206,7 @@ async def test_streamed_log_async_catches_up_once_after_stream_broke_off_and_run caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" - monkeypatch.setattr(StreamedLogAsync, '_reconnect_retry_s', 0) + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) run_client = Mock() @@ -2292,27 +2292,6 @@ def test_streamed_log_resumes_from_saved_last_redirected_at(caplog: LogCaptureFi assert _redirected_log_lines(caplog) == ['ACTOR: cut off before', 'ACTOR: logged after a long silence'] -def test_streamed_log_sync_backs_off_between_failing_reopens(monkeypatch: pytest.MonkeyPatch) -> None: - """The pause before reopening a stream doubles while reopened streams fail before delivering anything.""" - log_client = Mock() - log_client.stream.side_effect = [ - *_sync_streams([_LOG_BEFORE_DROP]), - *[ConnectionRefusedError('Simulated failure')] * 6, - *_sync_streams([_LOG_AFTER_DROP]), - ] - run_client = Mock() - run_client.get.side_effect = [_run_with_status('RUNNING')] * 7 + [_run_with_status('SUCCEEDED')] - streamed_log = StreamedLog( - log_client=log_client, to_logger=logging.getLogger('apify_client.tests.reopen_backoff'), run_client=run_client - ) - wait = Mock(return_value=False) - monkeypatch.setattr(streamed_log._stop_event, 'wait', wait) - - streamed_log._stream_log() - - assert [call.args[0] for call in wait.call_args_list] == [1, 2, 4, 8, 16, 30, 30] - - def test_logger_once_logs_the_first_call(caplog: LogCaptureFixture) -> None: """Test the first call with a given key is logged.""" logger = logging.getLogger('apify_client.tests.log_once_first') From 86429bf652e795afd013efc41e659b73ec4b04f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 10:24:37 +0000 Subject: [PATCH 11/17] refactor: stop log redirection once the run has finished, without a catch-up reopen Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- src/apify_client/_streamed_log.py | 20 +++----------- tests/unit/test_logging.py | 43 +++++++++++++------------------ 2 files changed, 22 insertions(+), 41 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index b41a7b05..2da67bd6 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -272,17 +272,14 @@ def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - reopened_after_finish = False while not self._stop_event.is_set(): - broke_off = False try: if not self._stream_log_once(): return except Exception as exc: if not self._may_reopen(): raise - broke_off = True - self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._to_logger.debug('Log stream broke off: %r', exc) if not self._received_data: self._stop_event.wait(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) @@ -296,12 +293,9 @@ def _stream_log(self) -> None: except Exception: self._flush_tail() raise - # A stream that broke off can miss the last messages of a run that finished meanwhile, so it is - # reopened once more to catch up. A stream that ended on its own carried the whole log. - if run_finished and (not broke_off or reopened_after_finish): + if run_finished: self._flush_tail() return - reopened_after_finish = run_finished self._prepare_reopen() self._stop_event.wait(self._reopen_pause_s) except Exception as exc: @@ -469,17 +463,14 @@ async def _stream_log(self) -> None: try: # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - reopened_after_finish = False while True: - broke_off = False try: if not await self._stream_log_once(): return except Exception as exc: if not self._may_reopen(): raise - broke_off = True - self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._to_logger.debug('Log stream broke off: %r', exc) if not self._received_data: await asyncio.sleep(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) @@ -491,12 +482,9 @@ async def _stream_log(self) -> None: except Exception: self._flush_tail() raise - # A stream that broke off can miss the last messages of a run that finished meanwhile, so it is - # reopened once more to catch up. A stream that ended on its own carried the whole log. - if run_finished and (not broke_off or reopened_after_finish): + if run_finished: self._flush_tail() return - reopened_after_finish = run_finished self._prepare_reopen() await asyncio.sleep(self._reopen_pause_s) except asyncio.CancelledError: diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 53eea814..a16fe297 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -1204,18 +1204,9 @@ def generate_logs() -> Iterator[bytes]: def _register_timing_out_log_stream(httpserver: HTTPServer, release_server: threading.Event) -> None: - """Serve a log stream that stalls past the client-side stream timeout, and the whole log to any reopened stream.""" - stream_requests: list[Request] = [] - - def handler(request: Request) -> Response: - stream_requests.append(request) - if len(stream_requests) > 1: - return Response( - b'2025-05-13T07:24:12.588Z ACTOR: still running\n2025-05-13T07:24:13.588Z ACTOR: finished\n', - status=200, - mimetype='application/octet-stream', - ) + """Serve a log stream that stalls past the client-side stream timeout.""" + def handler(_request: Request) -> Response: def generate_logs() -> Iterator[bytes]: # Emit one complete line, then keep the connection open (as a running Actor would) past the # client-side stream timeout without sending anything more. @@ -1241,7 +1232,7 @@ def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( http_client_class: type[HttpClient], monkeypatch: pytest.MonkeyPatch, ) -> None: - """A stream timeout neither leaks nor logs an error, and the reopened stream catches up with the finished run.""" + """A stream timeout of a finished run neither leaks nor logs an error, and ends the redirection.""" monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() @@ -1275,8 +1266,8 @@ def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( # The timeout is expected, so it must be swallowed quietly, not funnelled through the generic error handler. error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'sync thread logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout is redirected once, and the reopened stream adds the rest of the log. - assert _redirected_log_lines(caplog) == ['ACTOR: still running', 'ACTOR: finished'] + # The line received before the timeout is redirected, and the stream of the finished run is not reopened. + assert _redirected_log_lines(caplog) == ['ACTOR: still running'] @pytest.mark.usefixtures('propagate_stream_logs') @@ -1322,7 +1313,7 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( http_client_async_class: type[HttpClientAsync], monkeypatch: pytest.MonkeyPatch, ) -> None: - """A stream timeout neither raises nor logs an error, and the reopened stream catches up with the finished run.""" + """A stream timeout of a finished run neither raises nor logs an error, and ends the redirection.""" monkeypatch.setattr(StreamedLogAsync, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() @@ -1352,8 +1343,8 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( assert task.exception() is None, f'async streaming task raised on stream timeout: {task.exception()!r}' error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'async task logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout is redirected once, and the reopened stream adds the rest of the log. - assert _redirected_log_lines(caplog) == ['ACTOR: still running', 'ACTOR: finished'] + # The line received before the timeout is redirected, and the stream of the finished run is not reopened. + assert _redirected_log_lines(caplog) == ['ACTOR: still running'] _POLL_FAILURE_FINAL_SLEEP_S = 2 @@ -2182,16 +2173,17 @@ async def test_streamed_log_async_resumes_after_stream_closed_while_run_goes_on( assert log_client.stream.call_count == 2 -def test_streamed_log_sync_catches_up_once_after_stream_broke_off_and_run_finished( +def test_streamed_log_sync_reopens_stream_that_broke_off_while_run_goes_on( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" + """A stream that broke off while the run is running is reopened, and only the messages not redirected yet are + logged.""" monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) run_client = Mock() - run_client.get.return_value = _run_with_status('SUCCEEDED') - logger = logging.getLogger('apify_client.tests.catch_up_sync') + run_client.get.side_effect = [_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')] + logger = logging.getLogger('apify_client.tests.broke_off_sync') streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) with caplog.at_level(logging.DEBUG, logger=logger.name): @@ -2202,16 +2194,17 @@ def test_streamed_log_sync_catches_up_once_after_stream_broke_off_and_run_finish assert log_client.stream.call_count == 2 -async def test_streamed_log_async_catches_up_once_after_stream_broke_off_and_run_finished( +async def test_streamed_log_async_reopens_stream_that_broke_off_while_run_goes_on( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """A stream that broke off is reopened once to catch up with a run that has finished meanwhile.""" + """A stream that broke off while the run is running is reopened, and only the messages not redirected yet are + logged.""" monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) run_client = Mock() - run_client.get = AsyncMock(return_value=_run_with_status('SUCCEEDED')) - logger = logging.getLogger('apify_client.tests.catch_up_async') + run_client.get = AsyncMock(side_effect=[_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')]) + logger = logging.getLogger('apify_client.tests.broke_off_async') streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) with caplog.at_level(logging.DEBUG, logger=logger.name): From 3133679ae78fc4143af8bffabb23f9df57a1ede0 Mon Sep 17 00:00:00 2001 From: Josef Prochazka Date: Wed, 25 Nov 2026 11:32:58 +0100 Subject: [PATCH 12/17] Format --- src/apify_client/_streamed_log.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 2da67bd6..2f8ad7d5 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -276,28 +276,35 @@ def _stream_log(self) -> None: try: if not self._stream_log_once(): return + except Exception as exc: if not self._may_reopen(): raise + self._to_logger.debug('Log stream broke off: %r', exc) if not self._received_data: self._stop_event.wait(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) continue + if not self._may_reopen(): # `stop` may have landed after the ended stream kept its unterminated last line. self._flush_tail() return + try: run_finished = self._is_run_finished() except Exception: self._flush_tail() raise + if run_finished: self._flush_tail() return + self._prepare_reopen() self._stop_event.wait(self._reopen_pause_s) + except Exception as exc: if self._stop_event.is_set(): # `stop` closed the stream out from under the read, so the failure is expected. @@ -306,12 +313,15 @@ def _stream_log(self) -> None: # The stream cannot continue, so warn and let the thread end instead of leaking a traceback. self._to_logger.warning('Log streaming stopped: the log stream request timed out.') return + else: # Any other failure in log redirection must not escape the background thread; log it instead. self._to_logger.exception('Log redirection stopped due to unexpected error:') return + if self._received_data: return + # Stopped before any stream delivered a byte, which a run that finishes quickly can cause. try: self._process_whole_log(self._log_client.get_as_bytes(raw=True)) @@ -326,15 +336,17 @@ def _stream_log_once(self) -> bool: # Published so `stop` can close the response. self._log_stream = log_stream try: - # `stop` may have run before the response existed for it to close. A stream opened this late would - # end after its first chunk, so leave the log to the one-shot read of a session that has not received - # anything yet, or to the streams before this one. + # `stop` may have run before the response existed for it to close. No earlier stream delivered + # anything, and one opened this late would end after its first chunk, so read the whole log in one + # request. if self._stop_event.is_set(): return True + for data in log_stream.iter_bytes(): self._process_new_data(data) if self._stop_event.is_set(): break + finally: self._log_stream = None try: @@ -467,30 +479,38 @@ async def _stream_log(self) -> None: try: if not await self._stream_log_once(): return + except Exception as exc: if not self._may_reopen(): raise self._to_logger.debug('Log stream broke off: %r', exc) + if not self._received_data: await asyncio.sleep(retry_s) retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) continue + if not self._may_reopen(): return + try: run_finished = await self._is_run_finished() except Exception: self._flush_tail() raise + if run_finished: self._flush_tail() return + self._prepare_reopen() await asyncio.sleep(self._reopen_pause_s) + except asyncio.CancelledError: # `stop` cancelled the task, possibly while an ended stream kept its unterminated last line. self._flush_tail() raise + except Exception as exc: if self._log_client._http_client.is_timeout_error(exc): # noqa: SLF001 # A timeout on the long-lived stream is an expected terminal condition, not an error. @@ -504,6 +524,7 @@ async def _stream_log_once(self) -> bool: async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: if not log_stream: return False + try: async for data in log_stream.aiter_bytes(): self._process_new_data(data) From c6321463f0896ae180ab94cb957e0a1eca9efe2d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 11:34:36 +0000 Subject: [PATCH 13/17] refactor: reopen a log stream only when it broke off Measured on the platform: a log stream cut off for being idle always fails with a transport error (impit: `RemoteProtocolError`, after 330 s on the in-platform API URL and up to 360 s on the public one), while a stream that ends without an error has always delivered the whole log of a finished run. The run status read right after such a clean end was not terminal yet in 11 of 26 runs, so reopening on a non-terminal status downloaded the whole log a second time. The redirection now reopens a stream only when reading it failed after it had delivered data, and stops at a clean end. It no longer reads the run status, so `StreamedLog` no longer takes a `run_client`. Messages replayed by the reopened stream are skipped up to the last redirected timestamp without changing `since`. A stream timeout ends the redirection as before. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_017ocuAJFbkcdJ8X36dT46m4 --- docs/02_concepts/06_logging.mdx | 2 +- src/apify_client/_resource_clients/run.py | 4 +- src/apify_client/_streamed_log.py | 183 +++++++--------------- tests/unit/test_logging.py | 105 +++---------- 4 files changed, 85 insertions(+), 209 deletions(-) diff --git a/docs/02_concepts/06_logging.mdx b/docs/02_concepts/06_logging.mdx index 5c6c1c83..5da93e3e 100644 --- a/docs/02_concepts/06_logging.mdx +++ b/docs/02_concepts/06_logging.mdx @@ -79,7 +79,7 @@ For a run started with `ActorClient.start` By default, the whole log of the run is redirected. To redirect only part of it, pass a `datetime` as `since`, and only the lines logged at that time or later are redirected. A naive `datetime` is treated as UTC. The deprecated `from_start` argument still works: `from_start=False` is the same as `since=datetime.now(tz=UTC)`. -The platform closes a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client checks the run status and, if the run hasn't finished, reopens the stream. It then redirects only the lines logged after `StreamedLog.last_redirected_at`, the timestamp of the last redirected line. The reopened stream delivers the log from its start, and the client skips everything up to that point. +The platform cuts off a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client reopens the stream. The API can't continue a stream from a given point, so the reopened stream delivers the log from its start, and the client skips everything up to `StreamedLog.last_redirected_at`, the timestamp of the last redirected line. A stream that ends on its own has delivered the whole log of a finished run, and the client doesn't open it again. The same property lets you continue the redirection in another process, for example after the Actor that redirects the log reboots. Save `last_redirected_at` before the reboot, and afterwards pass it plus one millisecond as `since`. Log timestamps have millisecond precision, so this skips the last redirected line. It would also skip another line logged in that same millisecond and not yet redirected, which is rare. diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index caae8a1b..8947e81a 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -393,7 +393,7 @@ def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLog(log_client=self.log(), to_logger=to_logger, since=since, run_client=self) + return StreamedLog(log_client=self.log(), to_logger=to_logger, since=since) def charge( self, @@ -992,7 +992,7 @@ async def get_streamed_log( name = ' '.join(part for part in (actor_name, run_id) if part) to_logger = create_redirect_logger(f'apify.{name}') - return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, since=since, run_client=self) + return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, since=since) async def charge( self, diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 2f8ad7d5..81a04a91 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -6,17 +6,16 @@ import threading import warnings from asyncio import Task -from datetime import UTC, datetime, timedelta +from datetime import UTC, datetime from threading import Thread from typing import TYPE_CHECKING, ClassVar, Self from apify_client._docs import docs_group -from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES if TYPE_CHECKING: from types import TracebackType - from apify_client._resource_clients import LogClient, LogClientAsync, RunClient, RunClientAsync + from apify_client._resource_clients import LogClient, LogClientAsync from apify_client.http_clients import HttpResponse from apify_client.types import Timeout @@ -78,9 +77,10 @@ class StreamedLogBase: """Upper bound on the pause between reopens of an empty log stream.""" _reopen_pause_s: ClassVar[float] = 1 - """Pause before reopening a log stream that ended while the run was still going. + """Pause before reopening a log stream that broke off before its end. - The platform closes a log stream that has carried no data for several minutes, even though the run goes on. + The platform cuts off a log stream that has carried no data for several minutes, even though the run goes on. The + cut-off stream fails with a transport error, while the stream of a finished log ends without one. """ def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) -> None: @@ -92,6 +92,7 @@ def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) self._since = _as_utc(since) self._received_data = False self._last_redirected_at: datetime | None = None + self._replayed_until: datetime | None = None def _process_new_data(self, data: bytes) -> None: if data: @@ -125,6 +126,8 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: log_time = datetime.fromisoformat(decoded_marker) if self._since is not None and log_time < self._since: continue + if self._replayed_until is not None and log_time <= self._replayed_until: + continue message = decoded_marker + decoded_content self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) self._last_redirected_at = log_time @@ -132,21 +135,12 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: def _prepare_reopen(self) -> None: """Make the reopened stream redirect only the messages after the last redirected one. - The reopened stream replays the log from its start. Log timestamps have millisecond precision, so new messages - start one millisecond after `_last_redirected_at`. The unterminated line of the ended stream is dropped, since - the reopened stream delivers it in full. + The API cannot continue a log stream from a given point, so the reopened stream replays the log from its start. + The unterminated last line of the stream that broke off is dropped, since the reopened stream delivers it in + full. """ self._stream_buffer = [] - if self._last_redirected_at is not None: - self._since = self._last_redirected_at + timedelta(milliseconds=1) - - def _flush_tail(self) -> None: - """Redirect the unterminated last line, logging a failure instead of raising it.""" - try: - self._log_buffer_content(include_last_part=True) - except Exception: - # A truncated stream leaves an undecodable tail. - self._to_logger.exception('Log redirection stopped due to unexpected error:') + self._replayed_until = self._last_redirected_at def _process_whole_log(self, log: bytes | None) -> None: """Redirect a whole log read in one request, including its last part.""" @@ -186,7 +180,6 @@ def __init__( to_logger: logging.Logger, since: datetime | None = None, from_start: bool | None = None, - run_client: RunClient | None = None, ) -> None: """Initialize `StreamedLog`. @@ -197,13 +190,10 @@ def __init__( If `None`, the whole log is redirected. from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as `since=datetime.now(tz=UTC)`. Will be removed in v4. - run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is - still going is reopened, and the redirection resumes after the last redirected message. """ since = resolve_since(since=since, from_start=from_start) super().__init__(to_logger=to_logger, since=since) self._log_client = log_client - self._run_client = run_client self._streaming_thread: Thread | None = None self._log_stream: HttpResponse | None = None self._stop_event = threading.Event() @@ -270,41 +260,16 @@ def __exit__( def _stream_log(self) -> None: try: - # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s while not self._stop_event.is_set(): - try: - if not self._stream_log_once(): - return - - except Exception as exc: - if not self._may_reopen(): - raise - - self._to_logger.debug('Log stream broke off: %r', exc) - if not self._received_data: - self._stop_event.wait(retry_s) - retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) - continue - - if not self._may_reopen(): - # `stop` may have landed after the ended stream kept its unterminated last line. - self._flush_tail() - return - - try: - run_finished = self._is_run_finished() - except Exception: - self._flush_tail() - raise - - if run_finished: - self._flush_tail() + if not self._stream_log_once(): return - - self._prepare_reopen() - self._stop_event.wait(self._reopen_pause_s) - + if self._received_data: + self._stop_event.wait(self._reopen_pause_s) + continue + # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. + self._stop_event.wait(retry_s) + retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) except Exception as exc: if self._stop_event.is_set(): # `stop` closed the stream out from under the read, so the failure is expected. @@ -329,45 +294,44 @@ def _stream_log(self) -> None: self._to_logger.exception('Log redirection stopped due to unexpected error:') def _stream_log_once(self) -> bool: - """Redirect one log stream until it ends or `stop` is called. Return `False` when the log does not exist.""" + """Redirect one log stream until it ends or `stop` is called. Return whether the stream has to be opened again. + + A stream is opened again when it was empty, or when it broke off after it had delivered data. A stream that + ends without an error after delivering data carried the whole log of a finished run. + """ with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: if not log_stream: return False # Published so `stop` can close the response. self._log_stream = log_stream + broke_off = False try: # `stop` may have run before the response existed for it to close. No earlier stream delivered # anything, and one opened this late would end after its first chunk, so read the whole log in one # request. if self._stop_event.is_set(): return True - for data in log_stream.iter_bytes(): self._process_new_data(data) if self._stop_event.is_set(): break - + except Exception as exc: + is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 + if not self._received_data or is_timeout or self._stop_event.is_set(): + raise + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True finally: self._log_stream = None try: - # Flush the last buffered part even if the read timed out or was stopped. A stream that may be - # reopened keeps it until that is decided, since the reopened stream delivers it in full. - self._log_buffer_content(include_last_part=not self._may_reopen()) + # Flush the last buffered part even if the read timed out or was stopped. + self._log_buffer_content(include_last_part=True) except Exception: # A truncated stream leaves an undecodable tail, which is worth a traceback even while a stop is # in progress. self._to_logger.exception('Log redirection stopped due to unexpected error:') - return True - - def _may_reopen(self) -> bool: - """Return whether an ended stream may be reopened to resume the redirection.""" - return self._run_client is not None and self._received_data and not self._stop_event.is_set() - - def _is_run_finished(self) -> bool: - if self._run_client is None: - return True - run = self._run_client.get() - return run is None or run.status in _TERMINAL_STATUSES + return broke_off or not self._received_data @docs_group('Other') @@ -391,7 +355,6 @@ def __init__( to_logger: logging.Logger, since: datetime | None = None, from_start: bool | None = None, - run_client: RunClientAsync | None = None, ) -> None: """Initialize `StreamedLogAsync`. @@ -402,13 +365,10 @@ def __init__( If `None`, the whole log is redirected. from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as `since=datetime.now(tz=UTC)`. Will be removed in v4. - run_client: The client of the run whose log is streamed. With it, a log stream that ends while the run is - still going is reopened, and the redirection resumes after the last redirected message. """ since = resolve_since(since=since, from_start=from_start) super().__init__(to_logger=to_logger, since=since) self._log_client = log_client - self._run_client = run_client self._streaming_task: Task | None = None @property @@ -473,44 +433,14 @@ async def __aexit__( async def _stream_log(self) -> None: try: - # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. retry_s = self._empty_stream_retry_s - while True: - try: - if not await self._stream_log_once(): - return - - except Exception as exc: - if not self._may_reopen(): - raise - self._to_logger.debug('Log stream broke off: %r', exc) - - if not self._received_data: - await asyncio.sleep(retry_s) - retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) + while await self._stream_log_once(): + if self._received_data: + await asyncio.sleep(self._reopen_pause_s) continue - - if not self._may_reopen(): - return - - try: - run_finished = await self._is_run_finished() - except Exception: - self._flush_tail() - raise - - if run_finished: - self._flush_tail() - return - - self._prepare_reopen() - await asyncio.sleep(self._reopen_pause_s) - - except asyncio.CancelledError: - # `stop` cancelled the task, possibly while an ended stream kept its unterminated last line. - self._flush_tail() - raise - + # An empty stream means the run has not logged anything yet, so reopen it until the first bytes arrive. + await asyncio.sleep(retry_s) + retry_s = min(retry_s * 2, self._empty_stream_max_retry_s) except Exception as exc: if self._log_client._http_client.is_timeout_error(exc): # noqa: SLF001 # A timeout on the long-lived stream is an expected terminal condition, not an error. @@ -520,31 +450,30 @@ async def _stream_log(self) -> None: self._to_logger.exception('Log redirection stopped due to unexpected error:') async def _stream_log_once(self) -> bool: - """Redirect one log stream until it ends. Return `False` when the log does not exist.""" + """Redirect one log stream until it ends. Return whether the stream has to be opened again. + + A stream is opened again when it was empty, or when it broke off after it had delivered data. A stream that + ends without an error after delivering data carried the whole log of a finished run. + """ async with self._log_client.stream(raw=True, timeout=self._stream_timeout) as log_stream: if not log_stream: return False - + broke_off = False try: async for data in log_stream.aiter_bytes(): self._process_new_data(data) + except Exception as exc: + if not self._received_data or self._log_client._http_client.is_timeout_error(exc): # noqa: SLF001 + raise + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True finally: try: - # Flush the last buffered part even if the task is cancelled by `stop()`. A stream that may be - # reopened keeps it until that is decided, since the reopened stream delivers it in full. - self._log_buffer_content(include_last_part=not self._may_reopen()) + # Flush the last buffered part even if the task is cancelled by `stop()`. + self._log_buffer_content(include_last_part=True) except Exception: # A truncated stream leaves an undecodable tail. Keeping the failure here also keeps the # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. self._to_logger.exception('Log redirection stopped due to unexpected error:') - return True - - def _may_reopen(self) -> bool: - """Return whether an ended stream may be reopened to resume the redirection.""" - return self._run_client is not None and self._received_data - - async def _is_run_finished(self) -> bool: - if self._run_client is None: - return True - run = await self._run_client.get() - return run is None or run.status in _TERMINAL_STATUSES + return broke_off or not self._received_data diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index a16fe297..719f7721 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -1052,8 +1052,8 @@ async def test_async_watcher_aexit_skips_final_sleep_on_exception( _TAIL_SECOND_MESSAGE = '2025-05-13T07:24:13.132Z tail_test trailing partial line' -def _register_run_and_actor_endpoints(httpserver: HTTPServer, *, status: ActorJobStatus = 'RUNNING') -> None: - """Register the minimal run and actor endpoints required by `get_streamed_log`, with the run in `status`.""" +def _register_run_and_actor_endpoints(httpserver: HTTPServer) -> None: + """Register the minimal run and actor endpoints required by `get_streamed_log`.""" httpserver.expect_request(f'/v2/actor-runs/{_MOCKED_RUN_ID}', method='GET').respond_with_json( { 'data': { @@ -1062,7 +1062,7 @@ def _register_run_and_actor_endpoints(httpserver: HTTPServer, *, status: ActorJo 'userId': 'test_user_id', 'startedAt': '2019-11-30T07:34:24.202Z', 'finishedAt': '2019-12-12T09:30:12.202Z', - 'status': status, + 'status': 'RUNNING', 'statusMessage': 'Running', 'isStatusMessageTerminal': False, 'meta': {'origin': 'WEB'}, @@ -1232,12 +1232,12 @@ def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( http_client_class: type[HttpClient], monkeypatch: pytest.MonkeyPatch, ) -> None: - """A stream timeout of a finished run neither leaks nor logs an error, and ends the redirection.""" + """A stream timeout neither leaks nor logs an error, and ends the redirection without reopening the stream.""" monkeypatch.setattr(StreamedLog, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() _register_timing_out_log_stream(httpserver, release_server) - _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') + _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') http_client = http_client_class() @@ -1266,7 +1266,7 @@ def test_streamed_log_sync_does_not_leak_exception_on_stream_timeout( # The timeout is expected, so it must be swallowed quietly, not funnelled through the generic error handler. error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'sync thread logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout is redirected, and the stream of the finished run is not reopened. + # The line received before the timeout is redirected once, so the timed-out stream was not reopened. assert _redirected_log_lines(caplog) == ['ACTOR: still running'] @@ -1279,7 +1279,7 @@ def test_streamed_log_sync_requests_stream_with_no_timeout( httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' ).respond_with_data(b'2025-05-13T07:24:12.588Z ACTOR: done\n', content_type='application/octet-stream') - _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') + _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) @@ -1313,12 +1313,12 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( http_client_async_class: type[HttpClientAsync], monkeypatch: pytest.MonkeyPatch, ) -> None: - """A stream timeout of a finished run neither raises nor logs an error, and ends the redirection.""" + """A stream timeout neither raises nor logs an error, and ends the redirection without reopening the stream.""" monkeypatch.setattr(StreamedLogAsync, '_stream_timeout', timedelta(seconds=1)) release_server = threading.Event() _register_timing_out_log_stream(httpserver, release_server) - _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') + _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') http_client = http_client_async_class() @@ -1343,7 +1343,7 @@ async def test_streamed_log_async_does_not_error_on_stream_timeout( assert task.exception() is None, f'async streaming task raised on stream timeout: {task.exception()!r}' error_records = [r for r in caplog.records if r.levelno >= logging.ERROR and 'Log redirection stopped' in r.message] assert not error_records, f'async task logged an error on stream timeout: {[r.message for r in error_records]}' - # The line received before the timeout is redirected, and the stream of the finished run is not reopened. + # The line received before the timeout is redirected once, so the timed-out stream was not reopened. assert _redirected_log_lines(caplog) == ['ACTOR: still running'] @@ -1506,8 +1506,7 @@ def generate_logs() -> Iterator[bytes]: httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' ).respond_with_handler(_silent_handler) - # A finished run, so the stream that ends once the server is released is not reopened. - _register_run_and_actor_endpoints(httpserver, status='SUCCEEDED') + _register_run_and_actor_endpoints(httpserver) api_url = httpserver.url_for('/').removesuffix('/') run_client = ApifyClient(token='mocked_token', api_url=api_url).run(run_id=_MOCKED_RUN_ID) @@ -2064,7 +2063,7 @@ def test_streamed_log_treats_naive_since_as_utc() -> None: b'2025-05-13T07:24:12.588Z ACTOR: line 2\n' b'2025-05-13T07:24:13.000Z ACTOR: cut o' ) -"""What a log stream delivers before the platform closes it: two messages with the same timestamp, then a cut-off +"""What a log stream delivers before the platform cuts it off: two messages with the same timestamp, then a cut-off message.""" _LOG_AFTER_DROP = ( @@ -2085,10 +2084,6 @@ def test_streamed_log_treats_naive_since_as_utc() -> None: _LAST_LINE_TIME = datetime.fromisoformat('2025-05-13T07:34:13.000+00:00') -def _run_with_status(status: ActorJobStatus) -> Mock: - return Mock(status=status) - - def _sync_streams(*chunk_lists: list[bytes] | Exception) -> list[nullcontext]: """Return the log streams a mocked `LogClient.stream` opens, one per argument. @@ -2133,58 +2128,16 @@ async def failing_aiter(error: Exception = error) -> AsyncIterator[bytes]: return streams -def test_streamed_log_sync_resumes_after_stream_closed_while_run_goes_on( - caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" - monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) - log_client = Mock() - log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) - run_client = Mock() - run_client.get.side_effect = [_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')] - logger = logging.getLogger('apify_client.tests.resume_sync') - streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) - - with caplog.at_level(logging.DEBUG, logger=logger.name): - streamed_log._stream_log() - - assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME - assert streamed_log.last_redirected_at == _LAST_LINE_TIME - assert log_client.stream.call_count == 2 - - -async def test_streamed_log_async_resumes_after_stream_closed_while_run_goes_on( - caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch -) -> None: - """A stream that ends while the run is running is reopened, and only the messages not redirected yet are logged.""" - monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) - log_client = Mock() - log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP], [_LOG_AFTER_DROP]) - run_client = Mock() - run_client.get = AsyncMock(side_effect=[_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')]) - logger = logging.getLogger('apify_client.tests.resume_async') - streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) - - with caplog.at_level(logging.DEBUG, logger=logger.name): - await streamed_log._stream_log() - - assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME - assert streamed_log.last_redirected_at == _LAST_LINE_TIME - assert log_client.stream.call_count == 2 - - -def test_streamed_log_sync_reopens_stream_that_broke_off_while_run_goes_on( +def test_streamed_log_sync_reopens_stream_that_broke_off( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """A stream that broke off while the run is running is reopened, and only the messages not redirected yet are - logged.""" + """A stream that broke off is reopened, and only the messages not redirected yet are logged.""" monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) - run_client = Mock() - run_client.get.side_effect = [_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')] + log_client._http_client.is_timeout_error.return_value = False logger = logging.getLogger('apify_client.tests.broke_off_sync') - streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) with caplog.at_level(logging.DEBUG, logger=logger.name): streamed_log._stream_log() @@ -2194,18 +2147,16 @@ def test_streamed_log_sync_reopens_stream_that_broke_off_while_run_goes_on( assert log_client.stream.call_count == 2 -async def test_streamed_log_async_reopens_stream_that_broke_off_while_run_goes_on( +async def test_streamed_log_async_reopens_stream_that_broke_off( caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """A stream that broke off while the run is running is reopened, and only the messages not redirected yet are - logged.""" + """A stream that broke off is reopened, and only the messages not redirected yet are logged.""" monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) log_client = Mock() log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) - run_client = Mock() - run_client.get = AsyncMock(side_effect=[_run_with_status('RUNNING'), _run_with_status('SUCCEEDED')]) + log_client._http_client.is_timeout_error.return_value = False logger = logging.getLogger('apify_client.tests.broke_off_async') - streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) with caplog.at_level(logging.DEBUG, logger=logger.name): await streamed_log._stream_log() @@ -2215,14 +2166,12 @@ async def test_streamed_log_async_reopens_stream_that_broke_off_while_run_goes_o assert log_client.stream.call_count == 2 -def test_streamed_log_sync_does_not_reopen_stream_of_finished_run(caplog: LogCaptureFixture) -> None: - """A stream that ends on its own after the run finished is not reopened, and its last line is redirected.""" +def test_streamed_log_sync_does_not_reopen_stream_that_ended(caplog: LogCaptureFixture) -> None: + """A stream that ends without an error is not reopened, and its unterminated last line is redirected.""" log_client = Mock() log_client.stream.side_effect = _sync_streams([_LOG_BEFORE_DROP]) - run_client = Mock() - run_client.get.return_value = _run_with_status('SUCCEEDED') logger = logging.getLogger('apify_client.tests.finished_sync') - streamed_log = StreamedLog(log_client=log_client, to_logger=logger, run_client=run_client) + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) with caplog.at_level(logging.DEBUG, logger=logger.name): streamed_log._stream_log() @@ -2231,14 +2180,12 @@ def test_streamed_log_sync_does_not_reopen_stream_of_finished_run(caplog: LogCap log_client.stream.assert_called_once() -async def test_streamed_log_async_does_not_reopen_stream_of_finished_run(caplog: LogCaptureFixture) -> None: - """A stream that ends on its own after the run finished is not reopened, and its last line is redirected.""" +async def test_streamed_log_async_does_not_reopen_stream_that_ended(caplog: LogCaptureFixture) -> None: + """A stream that ends without an error is not reopened, and its unterminated last line is redirected.""" log_client = Mock() log_client.stream.side_effect = _async_streams([_LOG_BEFORE_DROP]) - run_client = Mock() - run_client.get = AsyncMock(return_value=_run_with_status('SUCCEEDED')) logger = logging.getLogger('apify_client.tests.finished_async') - streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger, run_client=run_client) + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) with caplog.at_level(logging.DEBUG, logger=logger.name): await streamed_log._stream_log() From 3d4b57fd7408cbe9554aa6cf5a24fb1e10c09363 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 12:26:14 +0000 Subject: [PATCH 14/17] fix: do not reopen a log stream when processing its data fails Only a failed read of the stream means it broke off. A failure to process a received line, such as an undecodable byte, repeats on every replay, so treating it as a broken stream re-downloaded the whole log once a second until `stop`. It now ends the redirection with a logged error again. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_017ocuAJFbkcdJ8X36dT46m4 --- src/apify_client/_streamed_log.py | 49 ++++++++++++++++++++----------- tests/unit/test_logging.py | 35 ++++++++++++++++++++++ 2 files changed, 67 insertions(+), 17 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 81a04a91..5967141b 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -311,17 +311,23 @@ def _stream_log_once(self) -> bool: # request. if self._stop_event.is_set(): return True - for data in log_stream.iter_bytes(): - self._process_new_data(data) - if self._stop_event.is_set(): + chunks = iter(log_stream.iter_bytes()) + while not self._stop_event.is_set(): + # Only a failed read means the stream broke off. A failure to process the data would repeat on + # every replay, so it ends the redirection. + try: + data = next(chunks) + except StopIteration: + break + except Exception as exc: + is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 + if not self._received_data or is_timeout or self._stop_event.is_set(): + raise + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True break - except Exception as exc: - is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 - if not self._received_data or is_timeout or self._stop_event.is_set(): - raise - self._to_logger.debug('Log stream broke off, reopening it: %r', exc) - self._prepare_reopen() - broke_off = True + self._process_new_data(data) finally: self._log_stream = None try: @@ -460,14 +466,23 @@ async def _stream_log_once(self) -> bool: return False broke_off = False try: - async for data in log_stream.aiter_bytes(): + chunks = aiter(log_stream.aiter_bytes()) + while True: + # Only a failed read means the stream broke off. A failure to process the data would repeat on + # every replay, so it ends the redirection. + try: + data = await anext(chunks) + except StopAsyncIteration: + break + except Exception as exc: + is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 + if not self._received_data or is_timeout: + raise + self._to_logger.debug('Log stream broke off, reopening it: %r', exc) + self._prepare_reopen() + broke_off = True + break self._process_new_data(data) - except Exception as exc: - if not self._received_data or self._log_client._http_client.is_timeout_error(exc): # noqa: SLF001 - raise - self._to_logger.debug('Log stream broke off, reopening it: %r', exc) - self._prepare_reopen() - broke_off = True finally: try: # Flush the last buffered part even if the task is cancelled by `stop()`. diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 719f7721..bfd4b2a1 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2166,6 +2166,41 @@ async def test_streamed_log_async_reopens_stream_that_broke_off( assert log_client.stream.call_count == 2 +_LOG_WITH_INVALID_UTF8 = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n2025-05-13T07:24:13.000Z ACTOR: bad \xff byte\n' + + +def test_streamed_log_sync_does_not_reopen_stream_with_unprocessable_line(caplog: LogCaptureFixture) -> None: + """A line that fails to be processed ends the redirection with a logged error, and the stream is not reopened.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams([_LOG_WITH_INVALID_UTF8]) + log_client._http_client.is_timeout_error.return_value = False + logger = logging.getLogger('apify_client.tests.unprocessable_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_with_unprocessable_line(caplog: LogCaptureFixture) -> None: + """A line that fails to be processed ends the redirection with a logged error, and the stream is not reopened.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams([_LOG_WITH_INVALID_UTF8]) + log_client._http_client.is_timeout_error.return_value = False + logger = logging.getLogger('apify_client.tests.unprocessable_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + def test_streamed_log_sync_does_not_reopen_stream_that_ended(caplog: LogCaptureFixture) -> None: """A stream that ends without an error is not reopened, and its unterminated last line is redirected.""" log_client = Mock() From 8a0aedb27ae3569a0f15022fb08054abd1ada142 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 12:38:27 +0000 Subject: [PATCH 15/17] refactor: reopen a log stream only after a transient transport error A stream read that fails is reopened only when the HTTP client classifies the error as a retryable transport error that is not a timeout, instead of after any exception. The error both built-in transports raise when the platform cuts off an idle stream (`RemoteProtocolError`) is classified so. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_017ocuAJFbkcdJ8X36dT46m4 --- src/apify_client/_streamed_log.py | 16 +++++++++---- tests/unit/test_logging.py | 38 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 5967141b..4292c785 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -320,8 +320,7 @@ def _stream_log_once(self) -> bool: except StopIteration: break except Exception as exc: - is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 - if not self._received_data or is_timeout or self._stop_event.is_set(): + if not self._received_data or not self._is_broken_read(exc) or self._stop_event.is_set(): raise self._to_logger.debug('Log stream broke off, reopening it: %r', exc) self._prepare_reopen() @@ -339,6 +338,11 @@ def _stream_log_once(self) -> bool: self._to_logger.exception('Log redirection stopped due to unexpected error:') return broke_off or not self._received_data + def _is_broken_read(self, exc: Exception) -> bool: + """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" + http_client = self._log_client._http_client # noqa: SLF001 + return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) + @docs_group('Other') class StreamedLogAsync(StreamedLogBase): @@ -475,8 +479,7 @@ async def _stream_log_once(self) -> bool: except StopAsyncIteration: break except Exception as exc: - is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001 - if not self._received_data or is_timeout: + if not self._received_data or not self._is_broken_read(exc): raise self._to_logger.debug('Log stream broke off, reopening it: %r', exc) self._prepare_reopen() @@ -492,3 +495,8 @@ async def _stream_log_once(self) -> bool: # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. self._to_logger.exception('Log redirection stopped due to unexpected error:') return broke_off or not self._received_data + + def _is_broken_read(self, exc: Exception) -> bool: + """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" + http_client = self._log_client._http_client # noqa: SLF001 + return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index bfd4b2a1..5df5ad4e 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2136,6 +2136,7 @@ def test_streamed_log_sync_reopens_stream_that_broke_off( log_client = Mock() log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True logger = logging.getLogger('apify_client.tests.broke_off_sync') streamed_log = StreamedLog(log_client=log_client, to_logger=logger) @@ -2155,6 +2156,7 @@ async def test_streamed_log_async_reopens_stream_that_broke_off( log_client = Mock() log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP]) log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True logger = logging.getLogger('apify_client.tests.broke_off_async') streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) @@ -2166,6 +2168,42 @@ async def test_streamed_log_async_reopens_stream_that_broke_off( assert log_client.stream.call_count == 2 +def test_streamed_log_sync_does_not_reopen_stream_after_non_transient_read_error(caplog: LogCaptureFixture) -> None: + """A read error the transport does not classify as transient ends the redirection with a logged error.""" + log_client = Mock() + log_client.stream.side_effect = _sync_streams(ValueError('Simulated permanent failure')) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = False + logger = logging.getLogger('apify_client.tests.non_transient_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + +async def test_streamed_log_async_does_not_reopen_stream_after_non_transient_read_error( + caplog: LogCaptureFixture, +) -> None: + """A read error the transport does not classify as transient ends the redirection with a logged error.""" + log_client = Mock() + log_client.stream.side_effect = _async_streams(ValueError('Simulated permanent failure')) + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = False + logger = logging.getLogger('apify_client.tests.non_transient_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o'] + assert 'Log redirection stopped due to unexpected error:' in caplog.text + log_client.stream.assert_called_once() + + _LOG_WITH_INVALID_UTF8 = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n2025-05-13T07:24:13.000Z ACTOR: bad \xff byte\n' From f0517a9ffa5092bd31495a9f394307adab6b33f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:03:45 +0000 Subject: [PATCH 16/17] fix: keep lines sharing the last timestamp on reopen, and stop reopening a replay that makes no progress - A reopened stream skips the replayed messages by timestamp and by how many messages at the last timestamp were already redirected, so a stream that breaks off inside a group of same-millisecond lines loses none of them. - A reopened stream that breaks off again before it replays the last redirected line ends the redirection with a warning, instead of reopening and downloading the log again at the same point indefinitely. - The `from_start` deprecation warning uses `stacklevel=3`. - `_is_broken_read` moves to `StreamedLogBase`, the async `last_redirected_at` docstring names `RunClientAsync.get_streamed_log`, and a comment about `stop` no longer assumes that no earlier stream delivered data. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- src/apify_client/_streamed_log.py | 84 ++++++++++--- tests/unit/test_logging.py | 198 +++++++++++++++++++++++++++++- 2 files changed, 261 insertions(+), 21 deletions(-) diff --git a/src/apify_client/_streamed_log.py b/src/apify_client/_streamed_log.py index 4292c785..fcc8f990 100644 --- a/src/apify_client/_streamed_log.py +++ b/src/apify_client/_streamed_log.py @@ -16,12 +16,15 @@ from types import TracebackType from apify_client._resource_clients import LogClient, LogClientAsync - from apify_client.http_clients import HttpResponse + from apify_client.http_clients import HttpClient, HttpClientAsync, HttpResponse from apify_client.types import Timeout _ANSI_CODE = re.compile(r'\x1b\[[0-9;]*m') _LEVEL_PATTERN = re.compile(r'\b(CRITICAL|FATAL|ERROR|WARNING|WARN|INFO|DEBUG)\b') +_NO_PROGRESS_MESSAGE = ( + 'Log redirection stopped: the reopened log stream broke off again before it reached the last redirected line: %r' +) def _as_utc(value: datetime | None) -> datetime | None: @@ -45,7 +48,7 @@ def resolve_since(*, since: datetime | None, from_start: bool | None) -> datetim warnings.warn( 'The `from_start` argument is deprecated and will be removed in v4. Use `since` instead.', DeprecationWarning, - stacklevel=2, + stacklevel=3, ) if since is not None: raise ValueError('Pass only one of `since` and `from_start`.') @@ -92,7 +95,12 @@ def __init__(self, to_logger: logging.Logger, *, since: datetime | None = None) self._since = _as_utc(since) self._received_data = False self._last_redirected_at: datetime | None = None + # How many redirected messages carry `_last_redirected_at`. Several messages can share a millisecond. + self._redirected_at_last_timestamp = 0 + # What a reopened stream replays: the messages before `_replayed_until`, and the first `_replay_skip_count` + # messages at it. self._replayed_until: datetime | None = None + self._replay_skip_count = 0 def _process_new_data(self, data: bytes) -> None: if data: @@ -124,13 +132,44 @@ def _log_buffer_content(self, *, include_last_part: bool = False) -> None: decoded_marker = marker.decode('utf-8') decoded_content = content.decode('utf-8') log_time = datetime.fromisoformat(decoded_marker) - if self._since is not None and log_time < self._since: + if self._is_replayed(log_time): continue - if self._replayed_until is not None and log_time <= self._replayed_until: + if self._since is not None and log_time < self._since: continue message = decoded_marker + decoded_content self._to_logger.log(level=self._guess_log_level_from_message(message), msg=message.strip()) + self._remember_redirected(log_time) + + def _is_replayed(self, log_time: datetime) -> bool: + """Return whether a message of a reopened stream was already redirected before the stream was reopened. + + Trimming of a long log removes only its oldest lines, so the replay keeps the last redirected messages in their + order, and counting the ones at the last timestamp finds where the redirection left off. + """ + if self._replayed_until is None: + return False + if log_time < self._replayed_until: + return True + if log_time == self._replayed_until and self._replay_skip_count > 0: + self._replay_skip_count -= 1 + return True + self._replayed_until = None + return False + + def _remember_redirected(self, log_time: datetime) -> None: + if log_time == self._last_redirected_at: + self._redirected_at_last_timestamp += 1 + else: self._last_redirected_at = log_time + self._redirected_at_last_timestamp = 1 + + def _replay_caught_up(self) -> bool: + """Return whether the current stream got at least as far as the stream before it. + + A reopened stream that breaks off again before it replays the last redirected message makes no progress, and + reopening it again would most likely fail at the same point. + """ + return self._replayed_until is None or self._replay_skip_count == 0 def _prepare_reopen(self) -> None: """Make the reopened stream redirect only the messages after the last redirected one. @@ -141,6 +180,7 @@ def _prepare_reopen(self) -> None: """ self._stream_buffer = [] self._replayed_until = self._last_redirected_at + self._replay_skip_count = self._redirected_at_last_timestamp def _process_whole_log(self, log: bytes | None) -> None: """Redirect a whole log read in one request, including its last part.""" @@ -148,6 +188,11 @@ def _process_whole_log(self, log: bytes | None) -> None: self._process_new_data(log) self._log_buffer_content(include_last_part=True) + @staticmethod + def _is_broken_read(http_client: HttpClient | HttpClientAsync, exc: Exception) -> bool: + """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" + return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) + @staticmethod def _guess_log_level_from_message(message: str) -> int: """Return the first whole-word level name found in the message, ignoring ANSI colors. Default to INFO.""" @@ -306,9 +351,9 @@ def _stream_log_once(self) -> bool: self._log_stream = log_stream broke_off = False try: - # `stop` may have run before the response existed for it to close. No earlier stream delivered - # anything, and one opened this late would end after its first chunk, so read the whole log in one - # request. + # `stop` may have run before the response existed for it to close. A stream opened this late would end + # after its first chunk, so leave the log to the earlier streams, or to the one-shot read when none of + # them delivered anything. if self._stop_event.is_set(): return True chunks = iter(log_stream.iter_bytes()) @@ -320,8 +365,13 @@ def _stream_log_once(self) -> bool: except StopIteration: break except Exception as exc: - if not self._received_data or not self._is_broken_read(exc) or self._stop_event.is_set(): + http_client = self._log_client._http_client # noqa: SLF001 + broken_read = self._received_data and self._is_broken_read(http_client, exc) + if not broken_read or self._stop_event.is_set(): raise + if not self._replay_caught_up(): + self._to_logger.warning(_NO_PROGRESS_MESSAGE, exc) + break self._to_logger.debug('Log stream broke off, reopening it: %r', exc) self._prepare_reopen() broke_off = True @@ -338,11 +388,6 @@ def _stream_log_once(self) -> bool: self._to_logger.exception('Log redirection stopped due to unexpected error:') return broke_off or not self._received_data - def _is_broken_read(self, exc: Exception) -> bool: - """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" - http_client = self._log_client._http_client # noqa: SLF001 - return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) - @docs_group('Other') class StreamedLogAsync(StreamedLogBase): @@ -386,7 +431,7 @@ def last_redirected_at(self) -> datetime | None: """The timestamp of the last redirected log message, or `None` if nothing has been redirected yet. To continue the redirection later, for example after the Actor that redirects the log reboots, save it and - pass it plus one millisecond as `since` to `RunClient.get_streamed_log`. + pass it plus one millisecond as `since` to `RunClientAsync.get_streamed_log`. """ return self._last_redirected_at @@ -479,8 +524,12 @@ async def _stream_log_once(self) -> bool: except StopAsyncIteration: break except Exception as exc: - if not self._received_data or not self._is_broken_read(exc): + http_client = self._log_client._http_client # noqa: SLF001 + if not self._received_data or not self._is_broken_read(http_client, exc): raise + if not self._replay_caught_up(): + self._to_logger.warning(_NO_PROGRESS_MESSAGE, exc) + break self._to_logger.debug('Log stream broke off, reopening it: %r', exc) self._prepare_reopen() broke_off = True @@ -495,8 +544,3 @@ async def _stream_log_once(self) -> bool: # cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects. self._to_logger.exception('Log redirection stopped due to unexpected error:') return broke_off or not self._received_data - - def _is_broken_read(self, exc: Exception) -> bool: - """Return whether `exc`, raised while reading the stream, means the transport cut the stream off.""" - http_client = self._log_client._http_client # noqa: SLF001 - return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc) diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 5df5ad4e..7e2c6d06 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -2032,10 +2032,12 @@ def test_streamed_log_from_start_is_deprecated_alias_of_since( mocked_datetime.now.return_value = _REDIRECT_ATTACH_TIME monkeypatch.setattr('apify_client._streamed_log.datetime', mocked_datetime) - with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated'): + with pytest.warns(DeprecationWarning, match='`from_start` argument is deprecated') as warning_records: streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test'), from_start=from_start) assert streamed_log._since == expected_since + # The warning points at the code that passed the argument, so the default warning filters do not hide it. + assert warning_records[0].filename == __file__ def test_streamed_log_rejects_both_since_and_from_start() -> None: @@ -2267,6 +2269,200 @@ async def test_streamed_log_async_does_not_reopen_stream_that_ended(caplog: LogC log_client.stream.assert_called_once() +def _breaking_sync_stream(data: bytes) -> nullcontext: + """Return a mocked sync log stream that delivers `data` and then breaks off with a transport error.""" + + def iter_bytes() -> Iterator[bytes]: + yield data + raise ConnectionResetError('Simulated drop') + + log_stream = Mock() + log_stream.iter_bytes.side_effect = iter_bytes + return nullcontext(log_stream) + + +def _breaking_async_stream(data: bytes) -> nullcontext: + """Return a mocked async log stream that delivers `data` and then breaks off with a transport error.""" + + async def aiter_bytes() -> AsyncIterator[bytes]: + yield data + raise ConnectionResetError('Simulated drop') + + log_stream = Mock() + log_stream.aiter_bytes.side_effect = aiter_bytes + return nullcontext(log_stream) + + +def _mock_log_client_with_transient_errors() -> Mock: + log_client = Mock() + log_client._http_client.is_timeout_error.return_value = False + log_client._http_client.is_retryable_transport_error.return_value = True + return log_client + + +_TRACEBACK_BEFORE_DROP = ( + b'2025-05-13T07:24:12.588Z Traceback (most recent call last):\n' + b'2025-05-13T07:24:12.588Z File "main.py", line 1, in \n' + b'2025-05-13T07:24:12.588Z ValueEr' +) +"""A traceback whose lines share one millisecond, cut off in its last line.""" + +_TRACEBACK_REPLAY = ( + b'2025-05-13T07:24:12.588Z Traceback (most recent call last):\n' + b'2025-05-13T07:24:12.588Z File "main.py", line 1, in \n' + b'2025-05-13T07:24:12.588Z ValueError: boom\n' + b'2025-05-13T07:24:13.000Z ACTOR: Exiting\n' +) + +_TRACEBACK_LINES = [ + 'Traceback (most recent call last):', + ' File "main.py", line 1, in ', + 'ValueError: boom', + 'ACTOR: Exiting', +] + + +def test_streamed_log_sync_reopen_keeps_lines_sharing_the_last_timestamp( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that breaks off inside a group of lines with the same timestamp loses none of them on reopen.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [_breaking_sync_stream(_TRACEBACK_BEFORE_DROP), *_sync_streams([_TRACEBACK_REPLAY])] + logger = logging.getLogger('apify_client.tests.same_timestamp_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _TRACEBACK_LINES + + +async def test_streamed_log_async_reopen_keeps_lines_sharing_the_last_timestamp( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stream that breaks off inside a group of lines with the same timestamp loses none of them on reopen.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_TRACEBACK_BEFORE_DROP), + *_async_streams([_TRACEBACK_REPLAY]), + ] + logger = logging.getLogger('apify_client.tests.same_timestamp_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _TRACEBACK_LINES + + +_REPLAY_CUT_SHORT = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n' +"""A replay of `_LOG_BEFORE_DROP` that breaks off before it reaches the last redirected line.""" + + +def test_streamed_log_sync_stops_when_reopened_stream_breaks_before_catching_up( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reopened stream that breaks off before it replays the last redirected line ends the redirection with a + warning instead of reopening again.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_sync_stream(_LOG_BEFORE_DROP), + _breaking_sync_stream(_REPLAY_CUT_SHORT), + *_sync_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.no_progress_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2'] + assert log_client.stream.call_count == 2 + assert any( + record.levelno == logging.WARNING and 'before it reached the last redirected line' in record.message + for record in caplog.records + ) + + +async def test_streamed_log_async_stops_when_reopened_stream_breaks_before_catching_up( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reopened stream that breaks off before it replays the last redirected line ends the redirection with a + warning instead of reopening again.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_LOG_BEFORE_DROP), + _breaking_async_stream(_REPLAY_CUT_SHORT), + *_async_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.no_progress_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2'] + assert log_client.stream.call_count == 2 + assert any( + record.levelno == logging.WARNING and 'before it reached the last redirected line' in record.message + for record in caplog.records + ) + + +_SILENT_REPLAY = b'2025-05-13T07:24:12.588Z ACTOR: line 1\n2025-05-13T07:24:12.588Z ACTOR: line 2\n' +"""A replay of `_LOG_BEFORE_DROP` that reaches the last redirected line, after which the run logs nothing.""" + + +def test_streamed_log_sync_keeps_reopening_stream_of_silent_run( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A silent run whose stream breaks off repeatedly keeps its redirection, because every replay catches up.""" + monkeypatch.setattr(StreamedLog, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_sync_stream(_LOG_BEFORE_DROP), + _breaking_sync_stream(_SILENT_REPLAY), + _breaking_sync_stream(_SILENT_REPLAY), + *_sync_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.silent_run_sync') + streamed_log = StreamedLog(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 4 + assert not any(record.levelno >= logging.WARNING for record in caplog.records) + + +async def test_streamed_log_async_keeps_reopening_stream_of_silent_run( + caplog: LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A silent run whose stream breaks off repeatedly keeps its redirection, because every replay catches up.""" + monkeypatch.setattr(StreamedLogAsync, '_reopen_pause_s', 0) + log_client = _mock_log_client_with_transient_errors() + log_client.stream.side_effect = [ + _breaking_async_stream(_LOG_BEFORE_DROP), + _breaking_async_stream(_SILENT_REPLAY), + _breaking_async_stream(_SILENT_REPLAY), + *_async_streams([_LOG_AFTER_DROP]), + ] + logger = logging.getLogger('apify_client.tests.silent_run_async') + streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger) + + with caplog.at_level(logging.DEBUG, logger=logger.name): + await streamed_log._stream_log() + + assert _redirected_log_lines(caplog) == _LINES_AFTER_RESUME + assert log_client.stream.call_count == 4 + assert not any(record.levelno >= logging.WARNING for record in caplog.records) + + def test_streamed_log_last_redirected_at_is_none_before_any_message() -> None: """`last_redirected_at` is `None` until a message is redirected.""" streamed_log = StreamedLog(log_client=Mock(), to_logger=logging.getLogger('test')) From 27292976a2cfa6b6311e648559882266beaafa7f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:40:23 +0000 Subject: [PATCH 17/17] docs: drop the v4 upgrading guide until v4 is planned The removal of `from_start` is tracked in https://github.com/apify/apify-client-python/issues/1259. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- docs/04_upgrading/upgrading_to_v4.mdx | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 docs/04_upgrading/upgrading_to_v4.mdx diff --git a/docs/04_upgrading/upgrading_to_v4.mdx b/docs/04_upgrading/upgrading_to_v4.mdx deleted file mode 100644 index 0d1529b3..00000000 --- a/docs/04_upgrading/upgrading_to_v4.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -id: upgrading-to-v4 -title: Upgrading to v4 -description: Breaking changes and migration guide from v3 to v4. ---- - -import ApiLink from '@theme/ApiLink'; - -This guide lists the breaking changes between Apify Python API Client v3.x and v4.0. - -## `from_start` removed from log redirection - -The `from_start` argument of `RunClient.get_streamed_log()`, `StreamedLog`, and their async counterparts has been removed. Use `since`, which takes a `datetime` and redirects only the log lines logged at that time or later: - -```python -from datetime import UTC, datetime - -# Before -streamed_log = run_client.get_streamed_log(from_start=True) -streamed_log = run_client.get_streamed_log(from_start=False) - -# After -streamed_log = run_client.get_streamed_log() # or since=None -streamed_log = run_client.get_streamed_log(since=datetime.now(tz=UTC)) -``` - -`since` can also start the redirection from any other point in the run's log, for example `since=datetime.now(tz=UTC) - timedelta(minutes=5)` for the last five minutes. A naive `datetime` is treated as UTC.