Skip to content

Commit 43356e5

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ocuAJFbkcdJ8X36dT46m4
1 parent 3253e3c commit 43356e5

2 files changed

Lines changed: 50 additions & 4 deletions

File tree

‎src/apify_client/_streamed_log.py‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,7 @@ def _stream_log_once(self) -> bool:
320320
except StopIteration:
321321
break
322322
except Exception as exc:
323-
is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001
324-
if not self._received_data or is_timeout or self._stop_event.is_set():
323+
if not self._received_data or not self._is_broken_read(exc) or self._stop_event.is_set():
325324
raise
326325
self._to_logger.debug('Log stream broke off, reopening it: %r', exc)
327326
self._prepare_reopen()
@@ -339,6 +338,11 @@ def _stream_log_once(self) -> bool:
339338
self._to_logger.exception('Log redirection stopped due to unexpected error:')
340339
return broke_off or not self._received_data
341340

341+
def _is_broken_read(self, exc: Exception) -> bool:
342+
"""Return whether `exc`, raised while reading the stream, means the transport cut the stream off."""
343+
http_client = self._log_client._http_client # noqa: SLF001
344+
return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc)
345+
342346

343347
@docs_group('Other')
344348
class StreamedLogAsync(StreamedLogBase):
@@ -475,8 +479,7 @@ async def _stream_log_once(self) -> bool:
475479
except StopAsyncIteration:
476480
break
477481
except Exception as exc:
478-
is_timeout = self._log_client._http_client.is_timeout_error(exc) # noqa: SLF001
479-
if not self._received_data or is_timeout:
482+
if not self._received_data or not self._is_broken_read(exc):
480483
raise
481484
self._to_logger.debug('Log stream broke off, reopening it: %r', exc)
482485
self._prepare_reopen()
@@ -492,3 +495,8 @@ async def _stream_log_once(self) -> bool:
492495
# cancellation `stop` raised propagating, so the task ends up cancelled as asyncio expects.
493496
self._to_logger.exception('Log redirection stopped due to unexpected error:')
494497
return broke_off or not self._received_data
498+
499+
def _is_broken_read(self, exc: Exception) -> bool:
500+
"""Return whether `exc`, raised while reading the stream, means the transport cut the stream off."""
501+
http_client = self._log_client._http_client # noqa: SLF001
502+
return http_client.is_retryable_transport_error(exc) and not http_client.is_timeout_error(exc)

‎tests/unit/test_logging.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1997,6 +1997,7 @@ def test_streamed_log_sync_reopens_stream_that_broke_off(
19971997
log_client = Mock()
19981998
log_client.stream.side_effect = _sync_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP])
19991999
log_client._http_client.is_timeout_error.return_value = False
2000+
log_client._http_client.is_retryable_transport_error.return_value = True
20002001
logger = logging.getLogger('apify_client.tests.broke_off_sync')
20012002
streamed_log = StreamedLog(log_client=log_client, to_logger=logger)
20022003

@@ -2016,6 +2017,7 @@ async def test_streamed_log_async_reopens_stream_that_broke_off(
20162017
log_client = Mock()
20172018
log_client.stream.side_effect = _async_streams(ConnectionResetError('Simulated drop'), [_LOG_AFTER_DROP])
20182019
log_client._http_client.is_timeout_error.return_value = False
2020+
log_client._http_client.is_retryable_transport_error.return_value = True
20192021
logger = logging.getLogger('apify_client.tests.broke_off_async')
20202022
streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger)
20212023

@@ -2027,6 +2029,42 @@ async def test_streamed_log_async_reopens_stream_that_broke_off(
20272029
assert log_client.stream.call_count == 2
20282030

20292031

2032+
def test_streamed_log_sync_does_not_reopen_stream_after_non_transient_read_error(caplog: LogCaptureFixture) -> None:
2033+
"""A read error the transport does not classify as transient ends the redirection with a logged error."""
2034+
log_client = Mock()
2035+
log_client.stream.side_effect = _sync_streams(ValueError('Simulated permanent failure'))
2036+
log_client._http_client.is_timeout_error.return_value = False
2037+
log_client._http_client.is_retryable_transport_error.return_value = False
2038+
logger = logging.getLogger('apify_client.tests.non_transient_sync')
2039+
streamed_log = StreamedLog(log_client=log_client, to_logger=logger)
2040+
2041+
with caplog.at_level(logging.DEBUG, logger=logger.name):
2042+
streamed_log._stream_log()
2043+
2044+
assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o']
2045+
assert 'Log redirection stopped due to unexpected error:' in caplog.text
2046+
log_client.stream.assert_called_once()
2047+
2048+
2049+
async def test_streamed_log_async_does_not_reopen_stream_after_non_transient_read_error(
2050+
caplog: LogCaptureFixture,
2051+
) -> None:
2052+
"""A read error the transport does not classify as transient ends the redirection with a logged error."""
2053+
log_client = Mock()
2054+
log_client.stream.side_effect = _async_streams(ValueError('Simulated permanent failure'))
2055+
log_client._http_client.is_timeout_error.return_value = False
2056+
log_client._http_client.is_retryable_transport_error.return_value = False
2057+
logger = logging.getLogger('apify_client.tests.non_transient_async')
2058+
streamed_log = StreamedLogAsync(log_client=log_client, to_logger=logger)
2059+
2060+
with caplog.at_level(logging.DEBUG, logger=logger.name):
2061+
await streamed_log._stream_log()
2062+
2063+
assert _redirected_log_lines(caplog) == ['ACTOR: line 1', 'ACTOR: line 2', 'ACTOR: cut o']
2064+
assert 'Log redirection stopped due to unexpected error:' in caplog.text
2065+
log_client.stream.assert_called_once()
2066+
2067+
20302068
_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'
20312069

20322070

0 commit comments

Comments
 (0)