From 1cf3c6885f1735aab59e8aa884cb7cd31be4f86b Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Wed, 2 Dec 2026 22:01:02 +0000 Subject: [PATCH 1/3] return interrupted requests to the request queue --- docs/06_upgrading/upgrading_to_v2.md | 2 +- src/crawlee/autoscaling/_autoscaled_pool.py | 7 + src/crawlee/crawlers/_basic/_basic_crawler.py | 34 +++- .../crawlers/_basic/_context_pipeline.py | 25 +++ src/crawlee/crawlers/_basic/_crawler_run.py | 2 +- .../unit/autoscaling/test_autoscaled_pool.py | 28 ++- .../crawlers/_basic/test_basic_crawler.py | 159 ++++++++++++++++++ .../crawlers/_basic/test_context_pipeline.py | 85 ++++++++++ 8 files changed, 335 insertions(+), 7 deletions(-) diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index e0b980b763..fcfd9fde3b 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -586,7 +586,7 @@ async def main() -> None: ### A timeout or cancellation around `run()` raises -In v1, `crawler.run()` caught the cancellation of the task that awaited it and returned the final statistics. A timeout around `run()`, such as `asyncio.wait_for()` or `asyncio.timeout()`, that expired during the crawl didn't raise `TimeoutError`, and a task running `run()` returned the statistics even after `task.cancel()`. In v2, `run()` lets the requests in progress finish and then raises `CancelledError`, which a timeout turns into `TimeoutError`. Each further cancellation cancels one of the requests in progress, so an anyio cancel scope, which keeps sending it, cancels them all. A cancelled run doesn't log the final statistics or the error analysis, the same as a failed run. Ctrl+C still ends the crawl gracefully and returns the statistics. +In v1, `crawler.run()` caught the cancellation of the task that awaited it and returned the final statistics. A timeout around `run()`, such as `asyncio.wait_for()` or `asyncio.timeout()`, that expired during the crawl didn't raise `TimeoutError`, and a task running `run()` returned the statistics even after `task.cancel()`. In v2, `run()` lets the requests in progress finish and then raises `CancelledError`, which a timeout turns into `TimeoutError`. Each further cancellation cancels one of the requests in progress, so an anyio cancel scope, which keeps sending it, cancels them all. A cancelled request goes back to the request manager, and the next `run()` processes it again. A cancelled run doesn't log the final statistics or the error analysis, the same as a failed run. Ctrl+C still ends the crawl gracefully and returns the statistics. To limit how long a crawl runs and still get the statistics, stop the crawler when the time is up. The requests in progress still finish, so the crawl can end after the limit. diff --git a/src/crawlee/autoscaling/_autoscaled_pool.py b/src/crawlee/autoscaling/_autoscaled_pool.py index 9c837a108a..a5ac243d11 100644 --- a/src/crawlee/autoscaling/_autoscaled_pool.py +++ b/src/crawlee/autoscaling/_autoscaled_pool.py @@ -317,3 +317,10 @@ async def _worker_task(self, task_id: str) -> None: # Without a timeout, `wait_for` cannot time out - the error comes from the task function itself. raise self._logger.warning('Task timed out after %s seconds', self._TASK_TIMEOUT.total_seconds()) + except asyncio.CancelledError as exc: + # The pool skips cancelled tasks, so a `CancelledError` that the task function raised itself, such as by + # awaiting a future that something else cancelled, has to end the run as a failure. + current_task = asyncio.current_task() + if current_task is not None and current_task.cancelling() == 0: + raise RuntimeError('`CancelledError` was raised, although nothing cancelled the task') from exc + raise diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index 1f39aa1419..b837e227ce 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -11,7 +11,7 @@ import traceback from asyncio import CancelledError from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable, Sequence -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, suppress from datetime import timedelta from functools import cached_property, partial from http import HTTPStatus @@ -1719,6 +1719,38 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 if request is None: return + try: + await self.__process_request(request) + except BaseException: + # A request left in progress would hold up any later `run()` on the same request manager. A request marked + # as handled isn't reclaimed, since some request managers, such as the Apify platform queue, would process + # it again. The reclaim runs as a task, since anyio cancel scopes keep cancelling every await. + if not request.was_already_handled: + # Once the run has failed, the pool starts no new task that could take the reclaimed request before the + # error ends the run. A task that is being cancelled doesn't end the run, so it doesn't fail it. + current_task = asyncio.current_task() + if current_task is not None and current_task.cancelling() == 0: + self._run.fail() + reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request_manager, request)) + while not reclaim.done(): + with suppress(CancelledError): + await asyncio.shield(reclaim) + raise + + async def __reclaim_request_after_failure(self, request_manager: RequestManager, request: Request) -> None: + try: + await wait_for( + lambda: request_manager.reclaim_request(request), + timeout=self._internal_timeout, + timeout_message=f'Reclaiming request timed out after {self._internal_timeout.total_seconds()} seconds', + logger=self._logger, + ) + except (Exception, CancelledError): + # The caller awaits this task through a shield, so only the reclaim itself or the shutdown of the event loop + # can raise a `CancelledError` here. The original exception is raised anyway, so this one is only logged. + self._logger.warning('Failed to reclaim the unfinished request %s', request.url, exc_info=True) + + async def __process_request(self, request: Request) -> None: if not (await self._is_allowed_based_on_robots_txt_file(request.url)): self._logger.warning( 'Skipping request %s (%s) because it is disallowed based on robots.txt', request.url, request.unique_key diff --git a/src/crawlee/crawlers/_basic/_context_pipeline.py b/src/crawlee/crawlers/_basic/_context_pipeline.py index f84d286d9f..8c51c92e11 100644 --- a/src/crawlee/crawlers/_basic/_context_pipeline.py +++ b/src/crawlee/crawlers/_basic/_context_pipeline.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from typing import TYPE_CHECKING, Any, Generic, cast from typing_extensions import TypeVar @@ -20,6 +21,21 @@ TMiddlewareCrawlingContext = TypeVar('TMiddlewareCrawlingContext', bound=BasicCrawlingContext) +def _as_error_unless_cancelled(exc: asyncio.CancelledError) -> RuntimeError | None: + """Turn a `CancelledError` that no cancellation of the current task explains into an ordinary error. + + Code raises one when it awaits a future that something else cancelled, and the request is then retried and failed + like on any other error. Returns `None` when the task is being cancelled. + """ + task = asyncio.current_task() + if task is None or task.cancelling() > 0: + return None + + error = RuntimeError('`CancelledError` was raised, although nothing cancelled the task') + error.__cause__ = exc + return error + + class _Middleware(Generic[TMiddlewareCrawlingContext, TCrawlingContext]): """Helper wrapper class to make the middleware easily observable by open telemetry instrumentation.""" @@ -103,6 +119,10 @@ async def __call__( raise except Exception as e: raise ContextPipelineInitializationError(e, crawling_context) from e + except asyncio.CancelledError as e: + if (error := _as_error_unless_cancelled(e)) is None: + raise + raise ContextPipelineInitializationError(error, crawling_context) from error crawling_context = result cleanup_stack.append(middleware_instance) @@ -112,6 +132,11 @@ async def __call__( except Exception as e: final_consumer_exception = e raise RequestHandlerError(e, crawling_context) from e + except asyncio.CancelledError as e: + if (error := _as_error_unless_cancelled(e)) is None: + raise + final_consumer_exception = error + raise RequestHandlerError(error, crawling_context) from error finally: for middleware_instance in reversed(cleanup_stack): await middleware_instance.cleanup(final_consumer_exception) diff --git a/src/crawlee/crawlers/_basic/_crawler_run.py b/src/crawlee/crawlers/_basic/_crawler_run.py index 610b3a1023..b6b8752950 100644 --- a/src/crawlee/crawlers/_basic/_crawler_run.py +++ b/src/crawlee/crawlers/_basic/_crawler_run.py @@ -81,7 +81,7 @@ def stop_requested(self) -> bool: @property def failed(self) -> bool: - """Whether a request has failed while the crawler aborts on an error.""" + """Whether the run has failed, so that it takes no new requests.""" return self._failed async def dispatch_requests(self) -> None: diff --git a/tests/unit/autoscaling/test_autoscaled_pool.py b/tests/unit/autoscaling/test_autoscaled_pool.py index c35567c1b4..3509f8712b 100644 --- a/tests/unit/autoscaling/test_autoscaled_pool.py +++ b/tests/unit/autoscaling/test_autoscaled_pool.py @@ -782,16 +782,36 @@ async def run(_task_id: str) -> None: is_finished.assert_not_awaited() -async def test_propagates_task_timeout_error( +@pytest.mark.parametrize( + ('raised', 'expected_error', 'match'), + [ + pytest.param( + TimeoutError('Fetching a session from the pool timed out after 10 seconds'), + TimeoutError, + r'Fetching a session from the pool timed out', + id='timeout-error-propagates', + ), + pytest.param( + asyncio.CancelledError(), + RuntimeError, + r'nothing cancelled the task', + id='cancelled-error-fails-run', + ), + ], +) +async def test_propagates_task_function_error( make_concurrency_system: type[ConcurrencySystem], + raised: BaseException, + expected_error: type[Exception], + match: str, ) -> None: - """A `TimeoutError` raised by the task function propagates instead of being swallowed by the pool.""" + """A `TimeoutError` or `CancelledError` raised by the task function fails the run instead of being swallowed.""" started_count = 0 async def run(_task_id: str) -> None: nonlocal started_count started_count += 1 - raise TimeoutError('Fetching a session from the pool timed out after 10 seconds') + raise raised async with make_concurrency_system( ConcurrencySettings(min_concurrency=1, max_concurrency=1, desired_concurrency=1) @@ -804,7 +824,7 @@ async def run(_task_id: str) -> None: is_finished_function=lambda: future(started_count > 0), ) - with pytest.raises(TimeoutError, match=r'Fetching a session from the pool timed out'): + with pytest.raises(expected_error, match=match): await pool.run() diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index b03771aad5..c14498c568 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -642,6 +642,131 @@ async def error_handler(context: BasicCrawlingContext, error: Exception) -> None await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com']) +async def test_error_handler_crash_reclaims_request() -> None: + """A request whose error handler raised is reclaimed, and the failing run doesn't process it again.""" + crawler = BasicCrawler(configure_logging=False) + handler_calls = Mock() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_calls() + raise RuntimeError('Arbitrary crash for testing purposes') + + @crawler.error_handler + async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + raise RuntimeError('Crash in error handler') + + with pytest.raises(UserDefinedErrorHandlerError): + await crawler.run(['https://a.placeholder.com']) + + request_manager = await crawler.get_request_manager() + request = await request_manager.fetch_next_request() + assert request is not None + handler_calls.assert_called_once() + + +async def test_handled_request_skips_reclaim() -> None: + """A request already marked as handled isn't reclaimed when its failed request handler raises.""" + crawler = BasicCrawler(configure_logging=False, max_request_retries=0) + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + raise RuntimeError('Arbitrary crash for testing purposes') + + @crawler.failed_request_handler + async def failed_request_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + raise RuntimeError('Crash in failed request handler') + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', wraps=request_manager.reclaim_request) as reclaim_mock, + pytest.raises(UserDefinedErrorHandlerError), + ): + await crawler.run(['https://a.placeholder.com']) + + reclaim_mock.assert_not_awaited() + + +@pytest.mark.parametrize( + 'reclaim_error', + [ + pytest.param(RuntimeError('Reclaim failed'), id='error'), + pytest.param(asyncio.CancelledError(), id='cancelled-error'), + ], +) +async def test_failed_reclaim_after_crash_logged( + caplog: pytest.LogCaptureFixture, reclaim_error: BaseException +) -> None: + """A reclaim that fails after the processing of a request failed logs a warning.""" + crawler = BasicCrawler(configure_logging=False) + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + raise RuntimeError('Arbitrary crash for testing purposes') + + @crawler.error_handler + async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + raise RuntimeError('Crash in error handler') + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', side_effect=reclaim_error), + pytest.raises(UserDefinedErrorHandlerError), + ): + await crawler.run(['https://a.placeholder.com']) + + warnings = [ + record + for record in caplog.records + if record.levelno == logging.WARNING and 'Failed to reclaim the unfinished request' in record.message + ] + assert len(warnings) == 1 + assert warnings[0].exc_info is not None + + +async def test_handler_cancelled_error_fails_request() -> None: + """A `CancelledError` that the request handler raises itself is retried and then fails the request.""" + crawler = BasicCrawler(configure_logging=False, max_request_retries=1) + handler_calls = Mock() + failed_errors = list[Exception]() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_calls() + raise asyncio.CancelledError + + @crawler.failed_request_handler + async def failed_request_handler(_context: BasicCrawlingContext, error: Exception) -> None: + failed_errors.append(error) + + await crawler.run(['https://a.placeholder.com']) + + assert handler_calls.call_count == 2 + assert len(failed_errors) == 1 + assert isinstance(failed_errors[0].__cause__, asyncio.CancelledError) + + +async def test_cancelled_task_keeps_run_going() -> None: + """A request whose task was cancelled while the run goes on is reclaimed and handled in the same run.""" + crawler = BasicCrawler(configure_logging=False) + handler_calls = Mock() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_calls() + if handler_calls.call_count == 1: + task = asyncio.current_task() + assert task is not None + task.cancel() + await asyncio.sleep(0) + + stats = await crawler.run(['https://a.placeholder.com']) + + assert stats.requests_succeeded == 1 + + async def test_calls_failed_request_handler() -> None: crawler = BasicCrawler(max_request_retries=3) calls = list[tuple[BasicCrawlingContext, Exception]]() @@ -5070,6 +5195,40 @@ async def swallow_cancellation() -> None: await run_task +async def test_repeated_cancellation_reclaims_request() -> None: + """A request that a repeated cancellation of `run()` cuts short is reclaimed before `run()` raises.""" + crawler = BasicCrawler(configure_logging=False) + handler_started = asyncio.Event() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_started.set() + await asyncio.Event().wait() + + request_manager = await crawler.get_request_manager() + reclaim_request = request_manager.reclaim_request + + async def slow_reclaim(request: Request, *, forefront: bool = False) -> ProcessedRequest | None: + # Further cancellations land while the reclaim is still in progress. + await asyncio.sleep(0.1) + return await reclaim_request(request, forefront=forefront) + + with patch.object(request_manager, 'reclaim_request', side_effect=slow_reclaim): + run_task = asyncio.create_task(crawler.run(['https://a.placeholder.com'])) + await handler_started.wait() + + # Like an anyio cancel scope, cancel at every await until `run()` gives up. + while not run_task.done(): + run_task.cancel() + await asyncio.sleep(0) + + with pytest.raises(asyncio.CancelledError): + await run_task + + request = await request_manager.fetch_next_request() + assert request is not None + + async def test_sigint_after_caught_cancellation() -> None: """SIGINT ends the crawl gracefully even when the task that awaits `run()` caught an earlier cancellation.""" crawler = BasicCrawler( diff --git a/tests/unit/crawlers/_basic/test_context_pipeline.py b/tests/unit/crawlers/_basic/test_context_pipeline.py index ba13d21762..452167d516 100644 --- a/tests/unit/crawlers/_basic/test_context_pipeline.py +++ b/tests/unit/crawlers/_basic/test_context_pipeline.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import logging from dataclasses import dataclass from typing import TYPE_CHECKING @@ -208,3 +209,87 @@ async def step_2(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingC assert consumer.called assert not cleanup.called + + +@pytest.mark.parametrize( + ('in_middleware', 'expected_error'), + [ + pytest.param(False, RequestHandlerError, id='consumer'), + pytest.param(True, ContextPipelineInitializationError, id='middleware initialization'), + ], +) +async def test_wraps_stray_cancelled_error( + *, in_middleware: bool, expected_error: type[RequestHandlerError | ContextPipelineInitializationError] +) -> None: + """A `CancelledError` raised while nothing cancels the task is wrapped like any other error.""" + consumer = AsyncMock(side_effect=asyncio.CancelledError) + + async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]: + if in_middleware: + raise asyncio.CancelledError + yield context + + pipeline = ContextPipeline().compose(step) + context = BasicCrawlingContext( + request=Request.from_url(url='https://test.io/'), + send_request=AsyncMock(), + add_requests=AsyncMock(), + session=Session(), + proxy_info=AsyncMock(), + push_data=AsyncMock(), + use_state=AsyncMock(), + get_key_value_store=AsyncMock(), + log=logging.getLogger(), + register_deferred_cleanup=lambda _: None, + extend_timeout=AsyncMock(), + ) + + with pytest.raises(expected_error) as exc_info: + await pipeline(context, consumer) + + wrapped = exc_info.value.wrapped_exception + assert isinstance(wrapped, RuntimeError) + assert isinstance(wrapped.__cause__, asyncio.CancelledError) + + +@pytest.mark.parametrize( + 'in_middleware', + [ + pytest.param(False, id='consumer'), + pytest.param(True, id='middleware initialization'), + ], +) +async def test_task_cancellation_propagates(*, in_middleware: bool) -> None: + """The `CancelledError` of a task that is being cancelled propagates unwrapped.""" + started = asyncio.Event() + + async def wait_forever(_context: BasicCrawlingContext) -> None: + started.set() + await asyncio.Event().wait() + + async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]: + if in_middleware: + await wait_forever(context) + yield context + + pipeline = ContextPipeline().compose(step) + context = BasicCrawlingContext( + request=Request.from_url(url='https://test.io/'), + send_request=AsyncMock(), + add_requests=AsyncMock(), + session=Session(), + proxy_info=AsyncMock(), + push_data=AsyncMock(), + use_state=AsyncMock(), + get_key_value_store=AsyncMock(), + log=logging.getLogger(), + register_deferred_cleanup=lambda _: None, + extend_timeout=AsyncMock(), + ) + + pipeline_task = asyncio.create_task(pipeline(context, wait_forever)) + await started.wait() + pipeline_task.cancel() + + with pytest.raises(asyncio.CancelledError): + await pipeline_task From f2c3b1ab4b16e38a740fc6f031e3cfef8f65883b Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Thu, 3 Dec 2026 15:02:36 +0000 Subject: [PATCH 2/3] leave retrying request manager calls to the backends --- docs/06_upgrading/upgrading_to_v2.md | 16 ++ src/crawlee/_utils/recoverable_state.py | 1 - src/crawlee/_utils/wait.py | 35 ++- src/crawlee/crawlers/_basic/_basic_crawler.py | 71 ++++--- tests/unit/_utils/test_wait.py | 24 ++- .../crawlers/_basic/test_basic_crawler.py | 199 +++++++++++++++++- 6 files changed, 292 insertions(+), 54 deletions(-) diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index fcfd9fde3b..d0d7f4e904 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -197,6 +197,14 @@ When the error handler sets `context.request.no_retry`, the request now fails ri In the error handler, `context.request.retry_count` is the number of retries before the failed attempt. In v1, for errors other than `SessionError`, the crawler increased it before it called the error handler. +## A timeout in the error handling retries the request + +The crawler gives the handling of a failed request `internal_timeout` to finish, which `context.extend_timeout()` extends. The handling covers the `error_handler`, the `failed_request_handler`, and giving the request back to the request manager or marking it as failed. When the time runs out for a request that can still be retried, the crawler now logs a warning and retries the request. The attempt counts towards `max_request_retries`, and a `SessionError` retires the session. When the time runs out in the `failed_request_handler`, the request stays failed, and the crawler logs a warning and goes on. In v1, both timeouts ended the crawl, and the handling of a `SessionError` had no time limit. Any other timeout for a request with no retries left, such as in marking it as failed, still ends the crawl. + +## The crawler doesn't retry request manager or session pool calls + +The crawler now makes one attempt at each call to its request manager and its session pool: fetching the next request, marking a request as handled, giving it back, and taking a session. Each call gets `internal_timeout` to finish, which now also covers giving back a request deferred by a `RequestThrottledError`. In v1, the crawler made up to 3 attempts at fetching a request, marking it as handled or taking a session when the call raised an error other than a timeout. The storage backends retry transient errors on their own, the same as in Crawlee JS. `SqlStorageBackend` and `RedisStorageBackend` make up to 3 attempts at a failed database call. A custom request manager, request queue backend or session pool that can fail for a moment, such as over the network, should retry such errors itself. Otherwise, a single error ends the crawl. + ## `BasicCrawlingContext` requires `extend_timeout` `BasicCrawlingContext` has a new required field, `extend_timeout`. If you build a crawling context yourself, such as in a test, pass it as well. @@ -1401,6 +1409,10 @@ The per-minute rates of `StatisticsState`, `requests_succeeded_per_minute` and ` `StatisticsState.crawler_runtime_for_serialization` is removed, and the persisted `crawlerRuntimeMillis` value is a number of milliseconds instead of an ISO 8601 duration string. Read the runtime from the `crawler_runtime` property instead. Statistics persisted by v1 are still restored. +### A failed request is counted before the failed request handler runs + +The crawler now counts a request as failed in its statistics before the `failed_request_handler` runs. In v1, it counted the failure after the handler, so a handler that raised left it uncounted. + ### `persistence_enabled` no longer accepts `'explicit_only'` `persistence_enabled` of `Statistics` no longer accepts `'explicit_only'`. Pass `True` or `False`. The value isn't validated, so `'explicit_only'` now acts as `True` and saves the statistics on every `PERSIST_STATE` event and on exit. In v1, it restored them but never saved them. @@ -1592,6 +1604,10 @@ Each dataset logs the warning about unsupported arguments once for each set of a `RequestQueue.purge()` no longer logs the `Storage client "..." does not support purging the request queue.` warnings. It raises `NotImplementedError` instead. For details, see [`RequestQueue.purge` raises when the storage backend can't purge](#requestqueuepurge-raises-when-the-storage-backend-cant-purge). +The WARNING `: retrying (/3)` that the crawler logged before another attempt at fetching a request, taking a session or marking a request as handled is removed, since the crawler no longer retries these calls. For details, see [The crawler doesn't retry request manager or session pool calls](#the-crawler-doesnt-retry-request-manager-or-session-pool-calls). + +When the handling of a failed request that can still be retried times out, the crawler logs the WARNING `Retrying request to due to: ` and retries the request. When the `failed_request_handler` times out, the crawler logs the WARNING `The failed request handler of was cancelled: `. In v1, the crawler logged the ERROR `An exception occurred during handling of failed request. This places the crawler and its underlying storages into an unknown state and crawling will be terminated.` and ended the crawl. For details, see [A timeout in the error handling retries the request](#a-timeout-in-the-error-handling-retries-the-request). + A cancelled `run()` doesn't log `Final request statistics` or `Error analysis`. For details, see [A timeout or cancellation around `run()` raises](#a-timeout-or-cancellation-around-run-raises). The storage backends no longer log the `Failed to decode JSON value for key "..."` and `Failed to decode text value for key "..."` warnings. Instead, `KeyValueStore` raises `ValueError` for a record that isn't valid JSON, and replaces the bytes it can't decode in a text or JSON record. For details, see [Reading values](#reading-values). `RedisStorageBackend` no longer logs the `Metadata for key "..." is missing or invalid.` warning when it reads a key that has no record. diff --git a/src/crawlee/_utils/recoverable_state.py b/src/crawlee/_utils/recoverable_state.py index 4ca9d0e52a..531145bc8d 100644 --- a/src/crawlee/_utils/recoverable_state.py +++ b/src/crawlee/_utils/recoverable_state.py @@ -331,5 +331,4 @@ async def _with_timeout(self, operation: Callable[[], Awaitable[T]], description timeout=self._persistence_timeout, timeout_message=f"{description} under key '{self._persist_state_key}' timed out after " f'{self._persistence_timeout.total_seconds():g} seconds.', - logger=self._log, ) diff --git a/src/crawlee/_utils/wait.py b/src/crawlee/_utils/wait.py index 3a39d4853d..6596ccb577 100644 --- a/src/crawlee/_utils/wait.py +++ b/src/crawlee/_utils/wait.py @@ -19,33 +19,24 @@ async def wait_for( *, timeout: timedelta, timeout_message: str | None = None, - max_retries: int = 1, - logger: Logger, ) -> T: - """Wait for an async operation to complete. + """Wait for an async operation to complete, and cancel it once the timeout expires. - If the wait times out, `TimeoutError` is raised and the future is cancelled. - Optionally retry on error. + A `TimeoutError` that the operation raises itself keeps its message. Args: - operation: A function that returns the future to wait for. - timeout: How long should we wait before cancelling the future. - timeout_message: Message to be included in the `TimeoutError` in case of timeout. - max_retries: How many times should the operation be attempted. - logger: Used to report information about retries as they happen. + operation: A function that returns the awaitable to wait for. + timeout: How long to wait before cancelling the operation. + timeout_message: The message of the `TimeoutError` raised when the timeout expires. """ - for iteration in range(1, max_retries + 1): - try: - return await asyncio.wait_for(operation(), timeout.total_seconds()) - except TimeoutError as ex: - raise TimeoutError(timeout_message) from ex - except Exception as e: - if iteration == max_retries: - raise - - logger.warning('%s: retrying (%s/%s)', e, iteration, max_retries) - - raise RuntimeError('Unreachable code') + deadline = asyncio.timeout(timeout.total_seconds()) + try: + async with deadline: + return await operation() + except TimeoutError as ex: + if not deadline.expired(): + raise + raise TimeoutError(timeout_message) from ex async def wait_for_extendable( diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index b837e227ce..b55ad27bea 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -734,8 +734,6 @@ async def _get_session(self) -> Session: timeout=self._internal_timeout, timeout_message='Fetching a session from the pool timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - max_retries=3, - logger=self._logger, ) async def _get_session_by_id(self, session_id: str) -> Session | None: @@ -745,8 +743,6 @@ async def _get_session_by_id(self, session_id: str) -> Session | None: timeout=self._internal_timeout, timeout_message='Fetching a session from the pool timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - max_retries=3, - logger=self._logger, ) async def get_request_manager(self) -> RequestManager: @@ -1398,7 +1394,6 @@ async def _handle_request_retries( context: TCrawlingContext | BasicCrawlingContext, error: Exception, ) -> None: - request_manager = await self.get_request_manager() request = context.request # The session is retired before the request goes back to the queue, so that its retry can't get the same one. retire_session = isinstance(error, SessionError) @@ -1424,27 +1419,49 @@ async def _handle_request_retries( ) if retire_session: context.session.retire() - await request_manager.reclaim_request(request) + await self._reclaim_request(request) return if retire_session: context.session.retire() request.state = RequestState.ERROR await self._mark_request_as_handled(request) - await self._handle_failed_request(context, error) self._statistics.record_request_processing_failure(request.unique_key) + await self._handle_failed_request(context, error) async def _handle_request_error(self, context: TCrawlingContext | BasicCrawlingContext, error: Exception) -> None: + request = context.request + retry_count_before = request.retry_count + can_retry = self._should_retry_request(context, error) try: context.request.state = RequestState.ERROR_HANDLER - await wait_for_extendable( - partial(self._handle_request_retries, context, error), - timeout=self._internal_timeout, - timeout_message=lambda timeout: ( - f'Handling request failure timed out after {timeout.total_seconds()} seconds' - ), - ) + try: + await wait_for_extendable( + partial(self._handle_request_retries, context, error), + timeout=self._internal_timeout, + timeout_message=lambda timeout: ( + f'Handling request failure timed out after {timeout.total_seconds()} seconds' + ), + ) + except TimeoutError as timeout_error: + request.state = RequestState.ERROR + # A request that has already failed keeps its failure. One that can still be retried is retried, and + # the retry is counted, so that an error handler that always times out can't retry it forever. Any + # other timeout ends the crawl, as any other error here does. + if request.was_already_handled: + self._logger.warning( + 'The failed request handler of %s was cancelled: %s', request.url, timeout_error + ) + elif can_retry: + self._logger.warning('Retrying request to %s due to: %s', request.url, timeout_error) + if request.retry_count == retry_count_before: + request.retry_count += 1 + if isinstance(error, SessionError): + context.session.retire() + await self._reclaim_request(request) + else: + raise except UserDefinedErrorHandlerError: context.request.state = RequestState.ERROR raise @@ -1712,8 +1729,6 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 request_manager.fetch_next_request, timeout=self._internal_timeout, timeout_message=f'Fetching next request failed after {self._internal_timeout.total_seconds()} seconds', - logger=self._logger, - max_retries=3, ) if request is None: @@ -1731,20 +1746,15 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 current_task = asyncio.current_task() if current_task is not None and current_task.cancelling() == 0: self._run.fail() - reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request_manager, request)) + reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request)) while not reclaim.done(): with suppress(CancelledError): await asyncio.shield(reclaim) raise - async def __reclaim_request_after_failure(self, request_manager: RequestManager, request: Request) -> None: + async def __reclaim_request_after_failure(self, request: Request) -> None: try: - await wait_for( - lambda: request_manager.reclaim_request(request), - timeout=self._internal_timeout, - timeout_message=f'Reclaiming request timed out after {self._internal_timeout.total_seconds()} seconds', - logger=self._logger, - ) + await self._reclaim_request(request) except (Exception, CancelledError): # The caller awaits this task through a shield, so only the reclaim itself or the shutdown of the event loop # can raise a `CancelledError` here. The original exception is raised anyway, so this one is only logged. @@ -1920,8 +1930,7 @@ async def _defer_throttled_request(self, request: Request, error: RequestThrottl self._logger.debug( 'Deferring request because its domain is rate-limiting us. %s', error, extra=request_log_extra(request) ) - request_manager = await self.get_request_manager() - await request_manager.reclaim_request(request, forefront=True) + await self._reclaim_request(request, forefront=True) self._statistics.record_request_processing_deferral(request.unique_key) async def _run_request_handler(self, context: BasicCrawlingContext) -> None: @@ -2207,7 +2216,13 @@ async def _mark_request_as_handled(self, request: Request) -> None: timeout=self._internal_timeout, timeout_message='Marking request as handled timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - logger=self._logger, - max_retries=3, ) self._run.handled_request = True + + async def _reclaim_request(self, request: Request, *, forefront: bool = False) -> None: + request_manager = await self.get_request_manager() + await wait_for( + lambda: request_manager.reclaim_request(request, forefront=forefront), + timeout=self._internal_timeout, + timeout_message=f'Reclaiming request timed out after {self._internal_timeout.total_seconds()} seconds', + ) diff --git a/tests/unit/_utils/test_wait.py b/tests/unit/_utils/test_wait.py index 65c6af6ca4..1ec61b685b 100644 --- a/tests/unit/_utils/test_wait.py +++ b/tests/unit/_utils/test_wait.py @@ -3,8 +3,15 @@ import asyncio import logging from datetime import timedelta +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock -from crawlee._utils.wait import wait_for_all_tasks_to_finish +import pytest + +from crawlee._utils.wait import wait_for, wait_for_all_tasks_to_finish + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable async def test_zero_timeout_cancels_right_away() -> None: @@ -18,3 +25,18 @@ async def test_zero_timeout_cancels_right_away() -> None: ) assert task.cancelled() + + +@pytest.mark.parametrize( + ('operation', 'message'), + [ + pytest.param(lambda: asyncio.Event().wait(), 'Internal timeout', id='timeout-expired'), + pytest.param( + AsyncMock(side_effect=TimeoutError('Driver timed out')), 'Driver timed out', id='operation-timeout' + ), + ], +) +async def test_wait_for_timeout_message(operation: Callable[[], Awaitable[object]], message: str) -> None: + """The `timeout_message` replaces only the message of a timeout that `wait_for` raises itself.""" + with pytest.raises(TimeoutError, match=message): + await wait_for(operation, timeout=timedelta(seconds=0.05), timeout_message='Internal timeout') diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index c14498c568..c73b1d8b0c 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -623,7 +623,7 @@ async def handler(_context: BasicCrawlingContext) -> None: with patch.object(queue, 'reclaim_request', wraps=queue.reclaim_request) as reclaim_mock: await crawler.run(['https://a.placeholder.com']) - reclaim_mock.assert_awaited_once_with(ANY) + reclaim_mock.assert_awaited_once_with(ANY, forefront=False) async def test_handles_error_in_error_handler() -> None: @@ -666,7 +666,7 @@ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> No async def test_handled_request_skips_reclaim() -> None: - """A request already marked as handled isn't reclaimed when its failed request handler raises.""" + """A failed request is counted and isn't reclaimed when its failed request handler raises.""" crawler = BasicCrawler(configure_logging=False, max_request_retries=0) @crawler.router.default_handler @@ -685,6 +685,7 @@ async def failed_request_handler(_context: BasicCrawlingContext, _error: Excepti ): await crawler.run(['https://a.placeholder.com']) + assert crawler.statistics.state.requests_failed == 1 reclaim_mock.assert_not_awaited() @@ -726,6 +727,178 @@ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> No assert warnings[0].exc_info is not None +@pytest.mark.parametrize( + ('owner', 'method'), + [ + pytest.param('request_manager', 'fetch_next_request', id='fetch'), + pytest.param('request_manager', 'mark_request_as_handled', id='mark'), + pytest.param('session_pool', 'get_session', id='session'), + ], +) +async def test_failed_internal_call_not_retried(owner: str, method: str) -> None: + """A failing call to the request manager or the session pool ends the run without another attempt.""" + async with SessionPool() as session_pool: + crawler = BasicCrawler( + session_pool=session_pool, + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + request_handler=AsyncMock(), + ) + owners = {'request_manager': await crawler.get_request_manager(), 'session_pool': session_pool} + + with ( + patch.object(owners[owner], method, side_effect=RuntimeError('Internal call failed')) as call_mock, + pytest.raises(RuntimeError, match='Internal call failed'), + ): + await crawler.run(['https://a.placeholder.com']) + + assert call_mock.await_count == 1 + + +@pytest.mark.parametrize( + ('error', 'session_retired'), + [ + pytest.param(RuntimeError('Arbitrary crash for testing purposes'), False, id='error'), + pytest.param(SessionError('blocked'), True, id='session-error'), + ], +) +async def test_failure_timeout_retries_request( + caplog: pytest.LogCaptureFixture, error: Exception, *, session_retired: bool +) -> None: + """A request whose failure handling times out is retried and counted, and a session error retires its session.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=2, + ) + sessions = list[Session]() + observe = Mock() + + @crawler.router.default_handler + async def handler(context: BasicCrawlingContext) -> None: + sessions.append(context.session) + raise error + + @crawler.error_handler + async def error_handler(context: BasicCrawlingContext, _error: Exception) -> None: + observe(retry_count=context.request.retry_count, retired=sessions[0].retired) + if context.request.retry_count == 0: + await asyncio.Event().wait() + + with caplog.at_level(logging.WARNING, logger='crawlee'): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + messages = [record.getMessage() for record in caplog.records] + expected_warning = ( + 'Retrying request to https://a.placeholder.com due to: Handling request failure timed out after 1.0 seconds' + ) + assert messages.count(expected_warning) == 1 + assert observe.call_args_list == [call(retry_count=0, retired=False), call(retry_count=1, retired=session_retired)] + + +async def test_failure_timeout_counts_one_retry() -> None: + """A timeout after the retry was counted retries the request without counting it again.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=1, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + failed_request_handler = AsyncMock() + crawler.failed_request_handler(failed_request_handler) + request_manager = await crawler.get_request_manager() + reclaim_request = request_manager.reclaim_request + + async def reclaim_after_first_hang(request: Request, **kwargs: Any) -> ProcessedRequest | None: + if reclaim_mock.await_count == 1: + await asyncio.Event().wait() + return await reclaim_request(request, **kwargs) + + with patch.object(request_manager, 'reclaim_request', side_effect=reclaim_after_first_hang) as reclaim_mock: + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + context = failed_request_handler.call_args.args[0] + assert context.request.retry_count == 1 + + +async def test_failure_timeout_reclaim_fails() -> None: + """A reclaim that fails after a timed-out failure handling ends the crawl.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=1, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + + @crawler.error_handler + async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + await asyncio.Event().wait() + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', side_effect=RuntimeError('Reclaim failed')), + pytest.raises(RuntimeError, match='Reclaim failed'), + ): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + +async def test_final_failure_timeout_ends_crawl() -> None: + """A failure handling that times out for a request with no retries left ends the crawl.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=0, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + request_manager = await crawler.get_request_manager() + + async def hanging_mark(_request: Request) -> None: + await asyncio.Event().wait() + + with ( + patch.object(request_manager, 'mark_request_as_handled', side_effect=hanging_mark), + pytest.raises(TimeoutError, match='Handling request failure timed out'), + ): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + +async def test_failed_handler_timeout_warns(caplog: pytest.LogCaptureFixture) -> None: + """A failed request handler that times out logs a warning, the request stays failed, and the crawl goes on.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + max_request_retries=0, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + + @crawler.failed_request_handler + async def failed_request_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + await asyncio.Event().wait() + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', wraps=request_manager.reclaim_request) as reclaim_mock, + caplog.at_level(logging.WARNING, logger='crawlee'), + ): + stats = await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com']) + + messages = [record.getMessage() for record in caplog.records] + expected_warning = ( + 'The failed request handler of https://a.placeholder.com was cancelled: ' + 'Handling request failure timed out after 1.0 seconds' + ) + assert messages.count(expected_warning) == 1 + assert stats.requests_failed == 2 + reclaim_mock.assert_not_awaited() + + async def test_handler_cancelled_error_fails_request() -> None: """A `CancelledError` that the request handler raises itself is retried and then fails the request.""" crawler = BasicCrawler(configure_logging=False, max_request_retries=1) @@ -3313,6 +3486,7 @@ async def test_error_handler_extends_timeout() -> None: configuration=Configuration(internal_timeout=timedelta(seconds=1)), max_request_retries=1, ) + error_handler_finished = Mock() @crawler.router.default_handler async def handler(context: BasicCrawlingContext) -> None: @@ -3323,10 +3497,12 @@ async def handler(context: BasicCrawlingContext) -> None: async def error_handler(context: BasicCrawlingContext, _error: Exception) -> None: await context.extend_timeout(timedelta(seconds=10)) await asyncio.sleep(1.5) + error_handler_finished() stats = await crawler.run(['https://a.placeholder.com']) assert stats.requests_succeeded == 1 + error_handler_finished.assert_called_once() async def test_extend_timeout_extends_lock() -> None: @@ -4644,6 +4820,25 @@ async def handler(context: BasicCrawlingContext) -> None: reclaim_mock.assert_awaited_once_with(ANY, forefront=True) +async def test_deferred_reclaim_times_out(monkeypatch: pytest.MonkeyPatch) -> None: + """A reclaim of a deferred request that hangs times out after the internal timeout.""" + throttler = await open_throttler() + + async def hanging_reclaim(*_args: Any, **_kwargs: Any) -> None: + await asyncio.Event().wait() + + monkeypatch.setattr(throttler, 'reclaim_request', hanging_reclaim) + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + request_manager=throttler, + request_handler=AsyncMock(side_effect=RequestThrottledError), + ) + + with pytest.raises(TimeoutError, match='Reclaiming request timed out'): + await crawler.run([THROTTLED_URL]) + + @pytest.mark.parametrize( 'use_throttler', [ From c1c8fa25edc54d009bc206cbd228e1f19c31b3b9 Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Thu, 3 Dec 2026 20:35:28 +0000 Subject: [PATCH 3/3] retry the request when taking a session or storing its results fails --- docs/03_concepts/03_crawling_context.mdx | 2 + docs/06_upgrading/upgrading_to_v2.md | 16 +- src/crawlee/crawlers/_basic/_basic_crawler.py | 95 ++++++---- .../crawlers/_basic/test_basic_crawler.py | 164 ++++++++++++++++-- 4 files changed, 226 insertions(+), 51 deletions(-) diff --git a/docs/03_concepts/03_crawling_context.mdx b/docs/03_concepts/03_crawling_context.mdx index eda33f2e81..83604f394f 100644 --- a/docs/03_concepts/03_crawling_context.mdx +++ b/docs/03_concepts/03_crawling_context.mdx @@ -66,6 +66,8 @@ The example simulates a failure on the first attempt. The dataset ends up with a {BufferedResultsExample} +When committing the results or marking the request as handled fails, the crawler retries the request too. It writes the key-value store records first, then adds the requests, and pushes the dataset items last, so a retry after a failed commit pushes the items twice only when pushing them failed after some of them were stored. A retry after a failed mark runs the handler again on top of its committed results, so its items are pushed a second time. + A few parts of the context write directly, outside of the buffer: - Changes to the dictionary from `use_state` are visible to other handlers immediately and stay in place when the handler fails. diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index d0d7f4e904..40b6c5d8a0 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -203,7 +203,17 @@ The crawler gives the handling of a failed request `internal_timeout` to finish, ## The crawler doesn't retry request manager or session pool calls -The crawler now makes one attempt at each call to its request manager and its session pool: fetching the next request, marking a request as handled, giving it back, and taking a session. Each call gets `internal_timeout` to finish, which now also covers giving back a request deferred by a `RequestThrottledError`. In v1, the crawler made up to 3 attempts at fetching a request, marking it as handled or taking a session when the call raised an error other than a timeout. The storage backends retry transient errors on their own, the same as in Crawlee JS. `SqlStorageBackend` and `RedisStorageBackend` make up to 3 attempts at a failed database call. A custom request manager, request queue backend or session pool that can fail for a moment, such as over the network, should retry such errors itself. Otherwise, a single error ends the crawl. +The crawler now makes one attempt at each call to its request manager and its session pool: fetching the next request, marking a request as handled, giving it back, and taking a session. Each call gets `internal_timeout` to finish, which now also covers giving back a request deferred by a `RequestThrottledError`. In v1, the crawler made up to 3 attempts at fetching a request, marking it as handled or taking a session when the call raised an error other than a timeout. The storage backends retry transient errors on their own, the same as in Crawlee JS. `SqlStorageBackend` and `RedisStorageBackend` make up to 3 attempts at a failed database call. A custom request manager, request queue backend or session pool that can fail for a moment, such as over the network, should retry such errors itself. Otherwise, a single error ends the crawl, except an error in taking a session or in marking a request as handled after its handler succeeded, which fails only that request. + +## An error in taking a session or storing the results retries the request + +An error in taking a session for a request, in storing the results of its request handler or in marking it as handled after the handler succeeded now fails only that request. The crawler retries the request up to `max_request_retries` times and then passes it to the `failed_request_handler`, the same as Crawlee JS. In v1, such an error ended the crawl. The results are the records written to `context.get_key_value_store()`, the requests from `context.add_requests` and the items from `context.push_data`. Storing them now gets `internal_timeout` to finish, and a timeout retries the request like any other error. + +The `error_handler` and the `failed_request_handler` get a `BasicCrawlingContext`. When taking the session failed, its session is a retired one without a proxy, which isn't in the session pool. An error in storing the results or in marking the request doesn't mark the session as bad, since the session didn't cause it. In Crawlee JS, both errors mark the session as bad. An error from a session pool that is no longer active, such as one exited during the run, still ends the crawl. + +The crawler now writes the key-value store records first, then adds the requests, and pushes the dataset items last. In v1, it wrote the records last. A retry after a failed commit runs the request handler again. Its records overwrite the ones already written, and the request queue doesn't add the same request twice. The dataset items go last, so they're pushed twice only when pushing them failed after some of them were stored. Requests created with `always_enqueue=True` are added again, since each run of the handler gives them a new unique key. A retry after a failed mark as handled stores the results of the handler a second time, the same as in Crawlee JS. + +An outage of the session pool, the key-value store or the dataset now fails every request that needs it while the outage lasts. A failed request is marked as handled, so a later `run()` doesn't retry it. `run()` returns as usual, so check `requests_failed` in the statistics it returns. With `abort_on_error=True`, the crawler stops at the first such error. ## `BasicCrawlingContext` requires `extend_timeout` @@ -862,7 +872,7 @@ async def main() -> None: await crawler.run(['https://crawlee.dev/']) ``` -A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. A `context.send_request` call there goes without a proxy. +A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. So does a request for which taking a session failed, in its `error_handler` and `failed_request_handler`. A `context.send_request` call there goes without a proxy. ### `create_session_function` gets the session options @@ -1608,6 +1618,8 @@ The WARNING `: retrying (/3)` that the crawler logged before ano When the handling of a failed request that can still be retried times out, the crawler logs the WARNING `Retrying request to due to: ` and retries the request. When the `failed_request_handler` times out, the crawler logs the WARNING `The failed request handler of was cancelled: `. In v1, the crawler logged the ERROR `An exception occurred during handling of failed request. This places the crawler and its underlying storages into an unknown state and crawling will be terminated.` and ended the crawl. For details, see [A timeout in the error handling retries the request](#a-timeout-in-the-error-handling-retries-the-request). +An error in taking a session, in storing the results of the request handler or in marking a request as handled after the handler succeeded now leads to the WARNING `Retrying request to due to: `, or to the ERROR `Request to failed and reached maximum retries` once no retries are left. In v1, an error in storing the results or in marking the request logged the ERROR `An exception occurred during handling of a request. This places the crawler and its underlying storages into an unknown state and crawling will be terminated.` An error in storing the results or in marking the request also logs the new DEBUG message `Failed to store the request result` with the traceback. A commit that times out fails with `Committing the request handler result timed out after seconds`. For details, see [An error in taking a session or storing the results retries the request](#an-error-in-taking-a-session-or-storing-the-results-retries-the-request). + A cancelled `run()` doesn't log `Final request statistics` or `Error analysis`. For details, see [A timeout or cancellation around `run()` raises](#a-timeout-or-cancellation-around-run-raises). The storage backends no longer log the `Failed to decode JSON value for key "..."` and `Failed to decode text value for key "..."` warnings. Instead, `KeyValueStore` raises `ValueError` for a record that isn't valid JSON, and replaces the bytes it can't decode in a text or JSON record. For details, see [Reading values](#reading-values). `RedisStorageBackend` no longer logs the `Metadata for key "..." is missing or invalid.` warning when it reads a key that has no record. diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index b55ad27bea..3f6d0f52aa 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -180,7 +180,9 @@ class _BasicCrawlerOptions(TypedDict): """Maximum duration allowed for a single request handler to run. A router handler can override it.""" abort_on_error: NotRequired[bool] - """If True, the crawler stops immediately when any request handler error occurs.""" + """If True, the crawler stops immediately when processing any request fails, such as with an error in the request + handler or in storing its results. + """ configure_logging: NotRequired[bool] """If True, the crawler will set up logging infrastructure automatically, unless the root logger already has @@ -385,7 +387,8 @@ def __init__( statistics: A custom `Statistics` instance, allowing the use of non-default configuration. The crawler enters it on every run, so don't enter it yourself. Crawlers can share it only when they run one after another. - abort_on_error: If True, the crawler stops immediately when any request handler error occurs. + abort_on_error: If True, the crawler stops immediately when processing any request fails, such as with an + error in the request handler or in storing its results. keep_alive: If True, it will keep crawler alive even if there are no requests in queue. Use `crawler.stop()` to exit the crawler. configure_logging: If True, the crawler will set up logging infrastructure automatically, unless the root @@ -827,10 +830,11 @@ async def get_key_value_store( def error_handler( self, handler: ErrorHandler[TCrawlingContext | BasicCrawlingContext] ) -> ErrorHandler[TCrawlingContext]: - """Register a function to handle errors occurring in request handlers. + """Register a function to handle errors occurring in processing a request. - The error handler is invoked after a request handler error occurs and before a retry attempt. To fail the - request without a retry, set `context.request.no_retry` in the error handler. + The error handler is invoked after processing a request fails, such as with an error in the request handler or + in storing its results, and before a retry attempt. To fail the request without a retry, set + `context.request.no_retry` in the error handler. """ self._error_handler = self._wrap_handler_with_error_context(handler) return handler @@ -1429,7 +1433,13 @@ async def _handle_request_retries( self._statistics.record_request_processing_failure(request.unique_key) await self._handle_failed_request(context, error) - async def _handle_request_error(self, context: TCrawlingContext | BasicCrawlingContext, error: Exception) -> None: + async def _handle_request_error( + self, + context: TCrawlingContext | BasicCrawlingContext, + error: Exception, + *, + mark_session_bad: bool = True, + ) -> None: request = context.request retry_count_before = request.retry_count can_retry = self._should_retry_request(context, error) @@ -1475,7 +1485,7 @@ async def _handle_request_error(self, context: TCrawlingContext | BasicCrawlingC raise # A session error has already retired the session. - if not isinstance(error, SessionError): + if mark_session_bad and not isinstance(error, SessionError): context.session.mark_bad() async def _handle_failed_request(self, context: TCrawlingContext | BasicCrawlingContext, error: Exception) -> None: @@ -1645,14 +1655,16 @@ async def _commit_request_handler_result(self, context: BasicCrawlingContext) -> """Commit request handler result for the input `context`. Result is taken from `_context_result_map`.""" result = self._context_result_map[context] + # A retry after a failed commit overwrites the records and the request queue skips the requests it already has, + # but the items would be pushed again. So the items go last. + await self._commit_key_value_store_changes(result, get_kvs=self.get_key_value_store) + for add_requests_call in result.add_requests_calls: await self._add_requests(context, **add_requests_call) for push_data_call in result.push_data_calls: await self._push_data(**push_data_call) - await self._commit_key_value_store_changes(result, get_kvs=self.get_key_value_store) - self._logger.debug( 'Committed the request handler result', extra={ @@ -1775,16 +1787,25 @@ async def __process_request(self, request: Request) -> None: # https://github.com/apify/crawlee-python/issues/1739 # https://github.com/apify/crawlee-python/issues/2135 bound_session_unusable = False - if request.session_id: - session = await self._get_session_by_id(request.session_id) - if session is None: - bound_session_unusable = True - # The failed request handler gets the pool's unusable session, or a retired stand-in once it's dropped. - session = self._session_pool._state.current_value.sessions.get(request.session_id) # noqa: SLF001 + session_error: Exception | None = None + try: + if request.session_id: + session = await self._get_session_by_id(request.session_id) if session is None: - session = Session(id=request.session_id, retired=True) - else: - session = await self._get_session() + bound_session_unusable = True + # The failed request handler gets the pool's unusable session, or a retired stand-in once it's gone. + session = self._session_pool._state.current_value.sessions.get(request.session_id) # noqa: SLF001 + if session is None: + session = Session(id=request.session_id, retired=True) + else: + session = await self._get_session() + except Exception as error: + # A session pool that is no longer active can't serve any other request either. + if not self._session_pool.active: + raise + # The request fails with the error, and its handlers get a retired stand-in without a proxy. + session_error = error + session = Session(id=request.session_id, retired=True) proxy_info = session.proxy_info result = RequestHandlerRunResult(key_value_store_getter=self.get_key_value_store) @@ -1811,6 +1832,8 @@ async def __process_request(self, request: Request) -> None: request.state = RequestState.REQUEST_HANDLER try: + if session_error is not None: + raise ContextPipelineInitializationError(session_error, context) from session_error if bound_session_unusable: raise RequestCollisionError( f'The Session (id: {request.session_id}) bound to the Request is no longer usable' @@ -1819,18 +1842,6 @@ async def __process_request(self, request: Request) -> None: except TimeoutError as e: raise RequestHandlerError(e, context) from e - await self._commit_request_handler_result(context) - - request.state = RequestState.DONE - - await self._mark_request_as_handled(request) - - if session.is_usable: - session.mark_good() - - self._statistics.record_request_processing_success(request.unique_key) - self._logger.debug('Request handled', extra=request_log_extra(request)) - except RequestCollisionError as request_error: request.no_retry = True await self._handle_request_error(context, request_error) @@ -1877,6 +1888,30 @@ async def __process_request(self, request: Request) -> None: ) raise + else: + try: + await wait_for( + partial(self._commit_request_handler_result, context), + timeout=self._internal_timeout, + timeout_message='Committing the request handler result timed out after ' + f'{self._internal_timeout.total_seconds()} seconds', + ) + request.state = RequestState.DONE + await self._mark_request_as_handled(request) + except Exception as storage_error: + self._logger.debug( + 'Failed to store the request result', exc_info=storage_error, extra=request_log_extra(request) + ) + # A storage error isn't the session's fault. + await self._handle_request_error(context, storage_error, mark_session_bad=False) + return + + if session.is_usable: + session.mark_good() + + self._statistics.record_request_processing_success(request.unique_key) + self._logger.debug('Request handled', extra=request_log_extra(request)) + finally: for cleanup in deferred_cleanup: try: diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index c73b1d8b0c..5ba7acd96e 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -728,33 +728,159 @@ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> No @pytest.mark.parametrize( - ('owner', 'method'), + 'method', [ - pytest.param('request_manager', 'fetch_next_request', id='fetch'), - pytest.param('request_manager', 'mark_request_as_handled', id='mark'), - pytest.param('session_pool', 'get_session', id='session'), + pytest.param('fetch_next_request', id='fetch'), + pytest.param('mark_request_as_handled', id='mark'), ], ) -async def test_failed_internal_call_not_retried(owner: str, method: str) -> None: - """A failing call to the request manager or the session pool ends the run without another attempt.""" - async with SessionPool() as session_pool: - crawler = BasicCrawler( - session_pool=session_pool, - configure_logging=False, - concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), - request_handler=AsyncMock(), - ) - owners = {'request_manager': await crawler.get_request_manager(), 'session_pool': session_pool} +async def test_failed_internal_call_not_retried(method: str) -> None: + """A failing fetch of a request, or mark of a failed one, ends the run without another attempt.""" + crawler = BasicCrawler( + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + max_request_retries=0, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + request_manager = await crawler.get_request_manager() - with ( - patch.object(owners[owner], method, side_effect=RuntimeError('Internal call failed')) as call_mock, - pytest.raises(RuntimeError, match='Internal call failed'), - ): - await crawler.run(['https://a.placeholder.com']) + with ( + patch.object(request_manager, method, side_effect=RuntimeError('Internal call failed')) as call_mock, + pytest.raises(RuntimeError, match='Internal call failed'), + ): + await crawler.run(['https://a.placeholder.com']) assert call_mock.await_count == 1 +@pytest.mark.parametrize( + ('method', 'bound'), + [ + pytest.param('get_session', False, id='session'), + pytest.param('get_session_by_id', True, id='bound-session'), + ], +) +async def test_failed_session_lookup_retried(method: str, *, bound: bool) -> None: + """A failed session lookup retries the request, and the error handler gets a retired session without a proxy.""" + request_handler = AsyncMock() + error_handler = AsyncMock() + lookup_error = RuntimeError('Session lookup failed') + session_pool = SessionPool(proxy_configuration=ProxyConfiguration(proxy_urls=['http://proxy.placeholder.com:8000'])) + crawler = BasicCrawler(session_pool=session_pool, configure_logging=False, request_handler=request_handler) + crawler.error_handler(error_handler) + + async with session_pool: + session = await session_pool.get_session() + request = Request.from_url('https://a.placeholder.com', session_id=session.id if bound else None) + lookup = getattr(session_pool, method) + + async def fail_first_lookup(*args: Any) -> Session | None: + if lookup_mock.await_count == 1: + raise lookup_error + return await lookup(*args) + + with patch.object(session_pool, method, side_effect=fail_first_lookup) as lookup_mock: + await crawler.run([request]) + + request_handler.assert_awaited_once() + error_handler.assert_awaited_once() + context, error = error_handler.call_args.args + assert error is lookup_error + assert context.session.retired + assert context.proxy_info is None + + +async def test_lookup_in_exited_pool_ends_crawl() -> None: + """A session lookup in a session pool that was exited during the run ends the crawl.""" + session_pool = SessionPool() + crawler = BasicCrawler( + session_pool=session_pool, + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + ) + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + await session_pool.__aexit__(None, None, None) + + await session_pool.__aenter__() + + with pytest.raises(RuntimeError, match='is not active'): + await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com']) + + +@pytest.mark.parametrize( + ('step', 'pushed_items'), + [ + pytest.param('_commit_key_value_store_changes', 1, id='kvs'), + pytest.param('_add_requests', 1, id='rq'), + pytest.param('_mark_request_as_handled', 2, id='mark'), + ], +) +async def test_failed_storage_step_retried(monkeypatch: pytest.MonkeyPatch, step: str, pushed_items: int) -> None: + """A failed commit or mark retries the request without `mark_bad`, and only a failed mark pushes items twice.""" + crawler = BasicCrawler( + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + ) + + @crawler.router.default_handler + async def handler(context: BasicCrawlingContext) -> None: + if context.request.url == 'https://a.placeholder.com': + await context.add_requests(['https://b.placeholder.com']) + await context.push_data({'url': context.request.url}) + + commit_step = getattr(crawler, step) + + async def fail_first_step(*args: Any, **kwargs: Any) -> None: + if step_mock.await_count == 1: + raise RuntimeError('Storage failed') + await commit_step(*args, **kwargs) + + step_mock = AsyncMock(side_effect=fail_first_step) + monkeypatch.setattr(crawler, step, step_mock) + + with patch.object(Session, 'mark_bad') as mark_bad_mock: + async with asyncio.timeout(10): + stats = await crawler.run(['https://a.placeholder.com']) + + data = await crawler.get_data() + assert data.items == [{'url': 'https://a.placeholder.com'}] * pushed_items + assert stats.requests_succeeded == 2 + mark_bad_mock.assert_not_called() + + +async def test_commit_timeout_retries_request( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """A commit that times out retries the request.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + request_handler=AsyncMock(), + ) + commit_key_value_store_changes = crawler._commit_key_value_store_changes + + async def stall_first_commit(*args: Any, **kwargs: Any) -> None: + if commit_mock.await_count == 1: + await asyncio.sleep(5) + await commit_key_value_store_changes(*args, **kwargs) + + commit_mock = AsyncMock(side_effect=stall_first_commit) + monkeypatch.setattr(crawler, '_commit_key_value_store_changes', commit_mock) + + with caplog.at_level(logging.WARNING, logger='crawlee'): + stats = await crawler.run(['https://a.placeholder.com']) + + expected_warning = ( + 'Retrying request to https://a.placeholder.com due to: ' + 'Committing the request handler result timed out after 1.0 seconds' + ) + messages = [record.getMessage() for record in caplog.records] + assert len([message for message in messages if message.startswith(expected_warning)]) == 1 + assert stats.requests_succeeded == 1 + + @pytest.mark.parametrize( ('error', 'session_retired'), [