diff --git a/docs/03_concepts/02_requests.mdx b/docs/03_concepts/02_requests.mdx
index ef3ecbb7ef..882971095d 100644
--- a/docs/03_concepts/02_requests.mdx
+++ b/docs/03_concepts/02_requests.mdx
@@ -62,6 +62,8 @@ The second request is a duplicate of the first one, so the queue ends up with fi
When a request handler raises an exception, the crawler retries the request. It increments `retry_count` and returns the request to the queue. A request is retried until `retry_count` reaches the crawler's `max_request_retries` option, which defaults to 3. To set a different limit for a single request, pass `max_retries` to `from_url`. A request created with `no_retry=True` isn't retried at all, and neither are requests that failed with an HTTP client error status (4xx), except the status codes in the crawler's `blocked_status_codes` option (401, 403, and 429 by default), which retire the session and retry the request with another one. These retries count towards `max_request_retries` too.
+The request handler can also decide whether to retry. Raising a `NonRetryableError` fails the request without a retry and passes it to the failed request handler right away, without calling the error handler. A `RetryRequestError` does the opposite and retries the request even when it has no retries left, so a handler that raises it on every attempt retries the request forever. Only `no_retry` stops such a retry. These retries still increment `retry_count`, so an error of another type on a later attempt has fewer retries left.
+
When the retries run out, the crawler calls the failed request handler and marks the request as handled. For error handlers, failed request handlers, and the related options, see [Error handling](./error-handling).
## Crawl depth
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/03_concepts/08_pydantic_ai_crawler.mdx b/docs/03_concepts/08_pydantic_ai_crawler.mdx
index 3081a731f9..bafa194e74 100644
--- a/docs/03_concepts/08_pydantic_ai_crawler.mdx
+++ b/docs/03_concepts/08_pydantic_ai_crawler.mdx
@@ -173,4 +173,4 @@ The errors point at the cause:
`UnexpectedModelBehavior`, `ModelHTTPError`, and `UsageLimitExceeded` come from the model run and share the base `AgentRunError`, so catch it to handle any model failure in one place. `ValueError` is raised by the extractor itself, around the schema or `scope`, not by the model.
-An extraction error is an ordinary request error, so Crawlee retries the request up to `max_request_retries` (3 by default), re-running the extraction and repeating its token cost. For errors that won't pass on retry, such as a wrong API key or an unsupported schema, the retries only waste effort, so catch them in the handler to skip the page, or set `abort_on_error=True` to stop the crawl.
+An extraction error is an ordinary request error, so Crawlee retries the request up to `max_request_retries` (3 by default), re-running the extraction and repeating its token cost. For errors that won't pass on retry, such as a wrong API key or an unsupported schema, the retries only waste effort. Catch them in the handler to skip the page, or re-raise them as a `NonRetryableError` to fail the request without a retry. To stop the crawl instead, set `abort_on_error=True`.
diff --git a/docs/03_concepts/20_error_handling.mdx b/docs/03_concepts/20_error_handling.mdx
index 236b7099d8..cda82ef053 100644
--- a/docs/03_concepts/20_error_handling.mdx
+++ b/docs/03_concepts/20_error_handling.mdx
@@ -47,6 +47,8 @@ Here's how to turn off retries for non-network errors using `NonRetryableError` instead.
+
## Capturing page snapshots on errors
Debugging a failing request is much easier when you can see what the page looked like at the moment of failure. Set `save_error_snapshots=True` in the crawler's `Statistics` and Crawlee automatically captures a page snapshot on the first occurrence of each unique error. The snapshot can contain an HTML file and a JPEG screenshot of the page where the unhandled exception was raised, and it's saved to the default key-value store, or to the one named by the `persist_state_kvs_name` option of `Statistics`. Both `PlaywrightCrawler` and [HTTP crawlers](./http-crawlers) capture the HTML file, but only `PlaywrightCrawler` can capture a screenshot as well.
diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md
index e0b980b763..19580461d1 100644
--- a/docs/06_upgrading/upgrading_to_v2.md
+++ b/docs/06_upgrading/upgrading_to_v2.md
@@ -197,6 +197,30 @@ 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, 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.
+
+## An error in a middleware cleanup retries the request
+
+An error in the cleanup of a context pipeline middleware, the code after its `yield`, 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`. In v1, such an error ended the crawl, and in Crawlee JS it still does. The results of the request handler are stored only after the cleanups, so the failed attempt's results are dropped and the retry runs the handler again. The `error_handler` and the `failed_request_handler` get a `BasicCrawlingContext`. The error doesn't mark the session as bad, since the session didn't cause it.
+
+The pipeline also runs the remaining cleanups after one fails, while Crawlee JS stops at the first failed cleanup. A cleanup error doesn't replace a cancellation or an error that the request handler or a middleware has already raised. The crawler handles the earlier error or cancellation as usual and logs the cleanup error as a warning. The same goes for every cleanup error after the first one. In v1, the remaining cleanups didn't run, and the cleanup error replaced the earlier error or cancellation.
+
## `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.
@@ -586,7 +610,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.
@@ -854,7 +878,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
@@ -1401,6 +1425,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 +1620,14 @@ 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).
+
+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).
+
+An error in a middleware cleanup 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. It also logs the new DEBUG message `An exception occurred during the finalization of crawling context` with the traceback. A cleanup error after a cancellation, after an error that the request handler or a middleware raised, or after an earlier cleanup error, logs the new WARNING `Failed to clean up a middleware for the request ` with the traceback instead. In v1, a cleanup error 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.` For details, see [An error in a middleware cleanup retries the request](#an-error-in-a-middleware-cleanup-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/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..1da15edbcd 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
@@ -57,14 +57,17 @@
from crawlee._utils.web import is_status_code_client_error, is_status_code_server_error
from crawlee.autoscaling import ConcurrencyConsumer, ConcurrencySystem
from crawlee.errors import (
+ ContextPipelineFinalizationError,
ContextPipelineInitializationError,
ContextPipelineInterruptedError,
HttpClientStatusCodeError,
HttpStatusCodeError,
+ NonRetryableError,
PersistentRateLimitError,
RequestCollisionError,
RequestHandlerError,
RequestThrottledError,
+ RetryRequestError,
SessionError,
UserDefinedErrorHandlerError,
UserHandlerTimeoutError,
@@ -150,7 +153,8 @@ class _BasicCrawlerOptions(TypedDict):
max_request_retries: NotRequired[int]
"""Specifies the maximum number of retries allowed for a request if its processing fails.
This includes retries due to navigation errors, session and proxy errors, or errors thrown from user-supplied
- functions (`request_handler`, `pre_navigation_hooks` etc.)."""
+ functions (`request_handler`, `pre_navigation_hooks` etc.). A `RetryRequestError` retries the request even past
+ this limit."""
max_requests_per_crawl: NotRequired[int | None]
"""Maximum number of pages to open during a crawl. The crawl stops upon reaching this limit.
@@ -180,7 +184,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
@@ -355,7 +361,8 @@ def __init__(
request_handler: A callable responsible for handling requests.
max_request_retries: Specifies the maximum number of retries allowed for a request if its processing fails.
This includes retries due to navigation errors, session and proxy errors, or errors thrown from
- user-supplied functions (`request_handler`, `pre_navigation_hooks` etc.).
+ user-supplied functions (`request_handler`, `pre_navigation_hooks` etc.). A `RetryRequestError` retries
+ the request even past this limit.
max_requests_per_crawl: Maximum number of pages to open during a crawl. The crawl stops upon reaching
this limit. Setting this value can help avoid infinite loops in misconfigured crawlers. `None` means
no limit. Due to concurrency settings, the actual number of pages visited may slightly exceed
@@ -385,7 +392,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
@@ -734,8 +742,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 +751,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:
@@ -831,10 +835,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
@@ -1254,12 +1259,12 @@ async def _push_data(
await dataset.push_data(data, **kwargs)
def _should_retry_request(self, context: BasicCrawlingContext, error: Exception) -> bool:
- if context.request.no_retry:
+ if context.request.no_retry or isinstance(error, NonRetryableError):
return False
- # Do not retry on client errors.
- if isinstance(error, HttpClientStatusCodeError):
- return False
+ # The user asked for this retry, so the retry limit doesn't apply.
+ if isinstance(error, RetryRequestError):
+ return True
max_request_retries = context.request.max_retries
if max_request_retries is None:
@@ -1398,7 +1403,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 +1428,55 @@ 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:
+ 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)
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, unless
+ # the error is a `RetryRequestError`. 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
@@ -1458,7 +1490,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:
@@ -1628,14 +1660,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={
@@ -1699,6 +1733,10 @@ async def __is_task_ready_function(self) -> bool:
request_manager = await self.get_request_manager()
readiness = await request_manager.check_readiness()
+ # The run can fail while the request manager is being asked.
+ if self._run.failed:
+ return False
+
# Without a wake-up, a paced crawl would resume only at the pool's next poll.
if readiness.status == 'waiting' and readiness.ready_at is not None:
self._run.schedule_wake(readiness.ready_at)
@@ -1712,13 +1750,48 @@ 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:
return
+ deferred_cleanup: list[Callable[[], Awaitable[None]]] = []
+
+ try:
+ await self.__process_request(request, deferred_cleanup)
+ except BaseException:
+ # The error ends the run. Failing it first keeps the pool from starting new requests while the reclaim and
+ # the deferred cleanups, such as closing a page, still 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()
+
+ # 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:
+ reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request))
+ while not reclaim.done():
+ with suppress(CancelledError):
+ await asyncio.shield(reclaim)
+ raise
+ finally:
+ for cleanup in deferred_cleanup:
+ try:
+ await cleanup()
+ except Exception:
+ self._logger.exception('Error in deferred cleanup')
+
+ async def __reclaim_request_after_failure(self, request: Request) -> None:
+ try:
+ 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.
+ self._logger.warning('Failed to reclaim the unfinished request %s', request.url, exc_info=True)
+
+ async def __process_request(self, request: Request, deferred_cleanup: list[Callable[[], Awaitable[None]]]) -> 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
@@ -1733,21 +1806,28 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
# 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)
- deferred_cleanup: list[Callable[[], Awaitable[None]]] = []
-
context = BasicCrawlingContext(
request=request,
session=session,
@@ -1769,6 +1849,8 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
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'
@@ -1777,18 +1859,6 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
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)
@@ -1827,6 +1897,15 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
)
await self._handle_request_error(context, initialization_error.wrapped_exception)
+ except ContextPipelineFinalizationError as finalization_error:
+ self._logger.debug(
+ 'An exception occurred during the finalization of crawling context',
+ exc_info=finalization_error,
+ extra=request_log_extra(request),
+ )
+ # A middleware cleanup error isn't the session's fault.
+ await self._handle_request_error(context, finalization_error.wrapped_exception, mark_session_bad=False)
+
except Exception as internal_error:
self._logger.exception(
'An exception occurred during handling of a request. This places the crawler '
@@ -1835,12 +1914,29 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
)
raise
- finally:
- for cleanup in deferred_cleanup:
- try:
- await cleanup()
- except Exception:
- self._logger.exception('Error in deferred cleanup')
+ 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))
async def _report_rate_limit(self, request: Request, error: RequestThrottledError) -> bool:
"""Report a rate limit for the request's URL and check whether the request manager took responsibility for it.
@@ -1888,8 +1984,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:
@@ -2175,7 +2270,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/src/crawlee/crawlers/_basic/_context_pipeline.py b/src/crawlee/crawlers/_basic/_context_pipeline.py
index f84d286d9f..b5ab5cebdf 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,27 @@
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
+
+
+def _log_cleanup_error(crawling_context: BasicCrawlingContext, error: Exception) -> None:
+ crawling_context.log.warning(
+ 'Failed to clean up a middleware for the request %s', crawling_context.request.url, exc_info=error
+ )
+
+
class _Middleware(Generic[TMiddlewareCrawlingContext, TCrawlingContext]):
"""Helper wrapper class to make the middleware easily observable by open telemetry instrumentation."""
@@ -43,13 +65,20 @@ async def cleanup(self, final_consumer_exception: Exception | None) -> None:
try:
await self.generator.asend(final_consumer_exception)
except StopAsyncIteration:
- pass
+ return
except ContextPipelineInterruptedError as e:
- raise RuntimeError('Invalid state - pipeline interrupted in the finalization step') from e
+ error: Exception = RuntimeError('Invalid state - pipeline interrupted in the finalization step')
+ error.__cause__ = e
except Exception as e:
- raise ContextPipelineFinalizationError(e, self.output_context or self.input_context) from e
+ error = e
+ except asyncio.CancelledError as e:
+ if (stray_error := _as_error_unless_cancelled(e)) is None:
+ raise
+ error = stray_error
else:
- raise RuntimeError('The middleware yielded more than once')
+ error = RuntimeError('The middleware yielded more than once')
+
+ raise ContextPipelineFinalizationError(error, self.output_context or self.input_context) from error
@docs_group('Other')
@@ -85,11 +114,13 @@ async def __call__(
) -> None:
"""Run a crawling context through the middleware chain and pipe it into a consumer function.
- Exceptions from the consumer function are wrapped together with the final crawling context.
+ Exceptions from the consumer function are wrapped together with the final crawling context. A cleanup error
+ doesn't stop the remaining cleanups. It's raised only when no other exception is. Otherwise, it's logged.
"""
chain = list(self._middleware_chain())
cleanup_stack: list[_Middleware[Any]] = []
final_consumer_exception: Exception | None = None
+ consumer_succeeded = False
try:
for member in reversed(chain):
@@ -103,6 +134,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,9 +147,32 @@ 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
+
+ consumer_succeeded = True
finally:
+ cleanup_error: Exception | None = None
for middleware_instance in reversed(cleanup_stack):
- await middleware_instance.cleanup(final_consumer_exception)
+ try:
+ await middleware_instance.cleanup(final_consumer_exception)
+ except Exception as e:
+ if consumer_succeeded and cleanup_error is None:
+ cleanup_error = e
+ else:
+ _log_cleanup_error(crawling_context, e)
+ except BaseException:
+ # Another exception, such as a cancellation, propagates in place of the held cleanup error, so the
+ # held error is only logged.
+ if cleanup_error is not None:
+ _log_cleanup_error(crawling_context, cleanup_error)
+ raise
+
+ if cleanup_error is not None:
+ raise cleanup_error
def compose(
self,
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/src/crawlee/errors.py b/src/crawlee/errors.py
index 15bdc45499..a952c98e37 100644
--- a/src/crawlee/errors.py
+++ b/src/crawlee/errors.py
@@ -13,11 +13,13 @@
'ContextPipelineInterruptedError',
'HttpClientStatusCodeError',
'HttpStatusCodeError',
+ 'NonRetryableError',
'PersistentRateLimitError',
'ProxyError',
'RequestCollisionError',
'RequestHandlerError',
'RequestThrottledError',
+ 'RetryRequestError',
'ServiceConflictError',
'SessionError',
'UserDefinedErrorHandlerError',
@@ -35,6 +37,27 @@ class UserHandlerTimeoutError(UserDefinedErrorHandlerError):
"""Raised when a router fails due to user raised timeout. This is different from user-defined handler timing out."""
+@docs_group('Errors')
+class NonRetryableError(Exception):
+ """Raise it from the request handler to fail the request without a retry.
+
+ The crawler skips the error handler and passes the request to the failed request handler right away.
+ """
+
+
+@docs_group('Errors')
+class RetryRequestError(Exception):
+ """Raise it from the request handler to retry the request even when it has no retries left.
+
+ The retry increments `retry_count`, but neither `max_request_retries` nor the request's `max_retries` limits it, so
+ a request handler that raises it on every attempt retries the request forever. A request with `no_retry` set isn't
+ retried.
+ """
+
+ def __init__(self, message: str = "Request is being retried at the user's request") -> None:
+ super().__init__(message)
+
+
@docs_group('Errors')
class SessionError(Exception):
"""Errors of `SessionError` type retire the session of the request and trigger a regular retry.
@@ -76,8 +99,8 @@ def __init__(self, message: str, status_code: int) -> None:
@docs_group('Errors')
-class HttpClientStatusCodeError(HttpStatusCodeError):
- """Raised when the response status code indicates an client error."""
+class HttpClientStatusCodeError(HttpStatusCodeError, NonRetryableError):
+ """Raised when the response status code indicates a client error, which fails the request without a retry."""
@docs_group('Errors')
diff --git a/tests/integration/crawlers/_http/test_http_crawler.py b/tests/integration/crawlers/_http/test_http_crawler.py
index 56fd214925..e65b11a1e3 100644
--- a/tests/integration/crawlers/_http/test_http_crawler.py
+++ b/tests/integration/crawlers/_http/test_http_crawler.py
@@ -202,16 +202,6 @@ async def handler(context: HttpCrawlingContext) -> None:
}
-async def test_do_not_retry_on_client_errors(crawler: HttpCrawler, server_url: URL) -> None:
- await crawler.add_requests([str(server_url / 'status/400')])
- stats = await crawler.run()
-
- # by default, client errors are not retried
- assert stats.requests_failed == 1
- assert stats.retry_histogram == [1]
- assert stats.requests_total == 1
-
-
@pytest.mark.flaky(
reruns=3,
reason='Transient transport errors in CI can consume retry budget without registering a status code.',
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/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..eade42caf2 100644
--- a/tests/unit/crawlers/_basic/test_basic_crawler.py
+++ b/tests/unit/crawlers/_basic/test_basic_crawler.py
@@ -31,12 +31,14 @@
from crawlee._utils.time import SharedTimeout
from crawlee.autoscaling import AutoscaledPool, ConcurrencyConsumer, ConcurrencySystem
from crawlee.configuration import Configuration
-from crawlee.crawlers import BasicCrawler
+from crawlee.crawlers import BasicCrawler, ContextPipeline
from crawlee.errors import (
ContextPipelineInterruptedError,
+ NonRetryableError,
PersistentRateLimitError,
RequestCollisionError,
RequestThrottledError,
+ RetryRequestError,
SessionError,
UserDefinedErrorHandlerError,
)
@@ -70,7 +72,7 @@
from tests._utils import open_throttler_held_until_reclaim, poll_until_condition
if TYPE_CHECKING:
- from collections.abc import Sequence
+ from collections.abc import AsyncGenerator, Sequence
from pathlib import Path
from crawlee._types import JsonSerializable
@@ -257,27 +259,22 @@ async def handler(context: BasicCrawlingContext) -> None:
assert processed_no_requests_warnings(caplog) == []
-async def test_retries_failed_requests() -> None:
- crawler = BasicCrawler()
- calls = list[str]()
+@pytest.mark.parametrize(
+ ('crawler_kwargs', 'max_retries', 'expected_attempts'),
+ [
+ pytest.param({}, None, 4, id='default-limit'),
+ pytest.param({'max_request_retries': 0}, None, 1, id='crawler-limit'),
+ pytest.param({'max_request_retries': 0}, 1, 2, id='request-limit'),
+ ],
+)
+async def test_retry_limit(crawler_kwargs: dict[str, Any], max_retries: int | None, expected_attempts: int) -> None:
+ """A failing request is retried up to its `max_retries`, else the crawler's `max_request_retries`, 3 by default."""
+ handler_mock = AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes'))
+ crawler = BasicCrawler(request_handler=handler_mock, **crawler_kwargs)
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- calls.append(context.request.url)
+ await crawler.run([Request.from_url('https://a.placeholder.com', max_retries=max_retries)])
- if context.request.url == 'https://b.placeholder.com':
- raise RuntimeError('Arbitrary crash for testing purposes')
-
- await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
-
- assert calls == [
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- 'https://c.placeholder.com',
- 'https://b.placeholder.com',
- 'https://b.placeholder.com',
- 'https://b.placeholder.com',
- ]
+ assert handler_mock.await_count == expected_attempts
async def test_no_new_tasks_while_only_request_in_progress() -> None:
@@ -304,57 +301,55 @@ async def handler(context: BasicCrawlingContext) -> None:
assert 1 <= fetch_counter.call_count <= 4
-async def test_respects_no_retry() -> None:
- crawler = BasicCrawler(max_request_retries=2)
- calls = list[str]()
-
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- calls.append(context.request.url)
- raise RuntimeError('Arbitrary crash for testing purposes')
-
- await crawler.run(
- [
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- Request.from_url(url='https://c.placeholder.com', no_retry=True),
- ]
- )
+@pytest.mark.parametrize(
+ ('error', 'no_retry'),
+ [
+ pytest.param(RuntimeError('Arbitrary crash for testing purposes'), True, id='no-retry'),
+ pytest.param(NonRetryableError('Arbitrary crash for testing purposes'), False, id='non-retryable-error'),
+ pytest.param(RetryRequestError(), True, id='retry-request-error-with-no-retry'),
+ ],
+)
+async def test_request_fails_without_retry(error: Exception, *, no_retry: bool) -> None:
+ """A request with `no_retry` or a `NonRetryableError` fails at once, without the error handler."""
+ crawler = BasicCrawler()
+ handler_mock = AsyncMock(side_effect=error)
+ error_handler_mock = AsyncMock()
+ failed_request_handler_mock = AsyncMock()
+ crawler.router.default_handler(handler_mock)
+ crawler.error_handler(error_handler_mock)
+ crawler.failed_request_handler(failed_request_handler_mock)
- assert calls == [
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- 'https://c.placeholder.com',
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- ]
+ await crawler.run([Request.from_url('https://a.placeholder.com', no_retry=no_retry)])
+ handler_mock.assert_awaited_once()
+ error_handler_mock.assert_not_awaited()
+ failed_request_handler_mock.assert_awaited_once_with(ANY, error)
-async def test_respects_request_specific_max_retries() -> None:
- crawler = BasicCrawler(max_request_retries=0)
- calls = list[str]()
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- calls.append(context.request.url)
- raise RuntimeError('Arbitrary crash for testing purposes')
+@pytest.mark.parametrize(
+ 'max_retries',
+ [
+ pytest.param(None, id='crawler-limit'),
+ pytest.param(1, id='request-limit'),
+ ],
+)
+async def test_retry_request_error_skips_limit(max_retries: int | None) -> None:
+ """A `RetryRequestError` retries past the crawler or request limit, calls the error handler and counts retries."""
+ queue = await RequestQueue.open()
+ crawler = BasicCrawler(request_manager=queue, max_request_retries=1)
+ request = Request.from_url('https://a.placeholder.com', max_retries=max_retries)
+ handler_mock = AsyncMock(side_effect=[RetryRequestError(), RetryRequestError(), RetryRequestError(), None])
+ error_handler_mock = AsyncMock()
+ crawler.router.default_handler(handler_mock)
+ crawler.error_handler(error_handler_mock)
- await crawler.run(
- [
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- Request.from_url(url='https://c.placeholder.com', user_data={'__crawlee': {'maxRetries': 1}}),
- ]
- )
+ await crawler.run([request])
- assert calls == [
- 'https://a.placeholder.com',
- 'https://b.placeholder.com',
- 'https://c.placeholder.com',
- 'https://c.placeholder.com',
- ]
+ assert handler_mock.await_count == 4
+ assert error_handler_mock.await_count == 3
+ stored_request = await queue.get_request(request.unique_key)
+ assert stored_request is not None
+ assert stored_request.retry_count == 3
async def test_calls_error_handler() -> None:
@@ -394,26 +389,6 @@ async def error_handler(context: BasicCrawlingContext, error: Exception) -> None
assert [error_call.retry_count for error_call in calls] == [0, 1]
-async def test_calls_error_handler_for_session_errors() -> None:
- crawler = BasicCrawler(
- max_request_retries=1,
- )
-
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- raise SessionError('Arbitrary session error for testing purposes')
-
- error_handler_mock = AsyncMock()
-
- @crawler.error_handler
- async def error_handler(context: BasicCrawlingContext, error: Exception) -> None:
- await error_handler_mock(context, error)
-
- await crawler.run(['https://crawlee.dev'])
-
- assert error_handler_mock.call_count == 1
-
-
@pytest.mark.parametrize(
'error',
[
@@ -448,6 +423,7 @@ async def test_error_handler_return_ignored(error: Exception) -> None:
[
pytest.param(RuntimeError('Arbitrary crash for testing purposes'), id='regular-error'),
pytest.param(SessionError('Arbitrary session error for testing purposes'), id='session-error'),
+ pytest.param(RetryRequestError(), id='retry-request-error'),
],
)
async def test_error_handler_no_retry_fails(error: Exception) -> None:
@@ -455,7 +431,7 @@ async def test_error_handler_no_retry_fails(error: Exception) -> None:
queue = await RequestQueue.open()
crawler = BasicCrawler(request_manager=queue)
request = Request.from_url('https://a.placeholder.com')
- handler_mock = AsyncMock(side_effect=error)
+ handler_mock = AsyncMock(side_effect=[error, None])
failed_request_handler_mock = AsyncMock()
crawler.router.default_handler(handler_mock)
crawler.failed_request_handler(failed_request_handler_mock)
@@ -492,22 +468,6 @@ async def error_handler(context: BasicCrawlingContext, _error: Exception) -> Non
assert session.retired
-async def test_session_error_handler_exception_is_wrapped() -> None:
- """Exceptions from error_handler on a SessionError become UserDefinedErrorHandlerError."""
- crawler = BasicCrawler()
-
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- raise SessionError('blocked')
-
- @crawler.error_handler
- async def error_handler(context: BasicCrawlingContext, error: Exception) -> None:
- raise RuntimeError('Crash in session error handler')
-
- with pytest.raises(UserDefinedErrorHandlerError):
- await crawler.run(['https://a.placeholder.com'])
-
-
async def test_session_errors_spend_retries() -> None:
"""Session errors and other errors spend the same `max_request_retries` budget."""
request_handler = AsyncMock(
@@ -623,43 +583,562 @@ 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:
- crawler = BasicCrawler(max_request_retries=3)
+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:
- if context.request.url == 'https://b.placeholder.com':
- raise RuntimeError('Arbitrary crash for testing purposes')
+ 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:
+ 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', 'https://b.placeholder.com', 'https://c.placeholder.com'])
+ 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 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
+ 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'])
+
+ assert crawler.statistics.state.requests_failed == 1
+ 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
+
+
+@pytest.mark.parametrize(
+ 'method',
+ [
+ pytest.param('fetch_next_request', id='fetch'),
+ pytest.param('mark_request_as_handled', id='mark'),
+ ],
+)
+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(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
-async def test_calls_failed_request_handler() -> None:
- crawler = BasicCrawler(max_request_retries=3)
- calls = list[tuple[BasicCrawlingContext, Exception]]()
+
+@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://b.placeholder.com':
- raise RuntimeError('Arbitrary crash for testing purposes')
+ 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_cleanup_error_retries_request() -> None:
+ """A cleanup error drops the attempt's results, reaches the error handler and retries without `mark_bad`."""
+ cleanup_error = RuntimeError('Crash during middleware finalization')
+ cleanup = AsyncMock(side_effect=[cleanup_error, None])
+
+ async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
+ yield context
+ await cleanup()
+
+ async def push_url(context: BasicCrawlingContext) -> None:
+ await context.push_data({'url': context.request.url})
+
+ crawler = BasicCrawler(configure_logging=False, _context_pipeline=ContextPipeline().compose(step))
+ handler_mock = AsyncMock(side_effect=push_url)
+ crawler.router.default_handler(handler_mock)
+ error_handler_mock = AsyncMock()
+ crawler.error_handler(error_handler_mock)
+
+ with patch.object(Session, 'mark_bad') as mark_bad_mock:
+ await crawler.run(['https://a.placeholder.com'])
+
+ data = await crawler.get_data()
+ assert data.items == [{'url': 'https://a.placeholder.com'}]
+ assert handler_mock.await_count == 2
+ error_handler_mock.assert_awaited_once_with(ANY, cleanup_error)
+ 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'),
+ [
+ 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_skips_limit() -> None:
+ """A `RetryRequestError` whose failure handling times out is retried even with no retries left."""
+ crawler = BasicCrawler(
+ configuration=Configuration(internal_timeout=timedelta(seconds=1)),
+ configure_logging=False,
+ max_request_retries=0,
+ )
+ handler_mock = AsyncMock(side_effect=[RetryRequestError(), None])
+ crawler.router.default_handler(handler_mock)
+
+ @crawler.error_handler
+ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None:
+ await asyncio.Event().wait()
+
+ async with asyncio.timeout(10):
+ await crawler.run(['https://a.placeholder.com'])
+
+ assert handler_mock.await_count == 2
+
+
+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:
- calls.append((context, error))
+ async def failed_request_handler(_context: BasicCrawlingContext, _error: Exception) -> None:
+ await asyncio.Event().wait()
- await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
+ request_manager = await crawler.get_request_manager()
- assert len(calls) == 1
- assert calls[0][0].request.url == 'https://b.placeholder.com'
- assert isinstance(calls[0][1], RuntimeError)
+ 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)
+ 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
+
+
+@pytest.mark.parametrize(
+ ('max_request_retries', 'crashing_hook'),
+ [
+ pytest.param(1, 'error_handler', id='unhandled-request'),
+ pytest.param(0, 'failed_request_handler', id='handled-request'),
+ ],
+)
+async def test_failed_run_starts_no_new_request(max_request_retries: int, crashing_hook: str) -> None:
+ """An error that ends the run starts no new request while the deferred cleanup of the failed one still runs."""
+ crawler = BasicCrawler(
+ configure_logging=False,
+ max_request_retries=max_request_retries,
+ concurrency_settings=ConcurrencySettings(desired_concurrency=2, max_concurrency=2),
+ )
+ started_urls = list[str]()
+
+ async def close_page() -> None:
+ await asyncio.sleep(0.5)
+
+ cleanup = AsyncMock(side_effect=close_page)
+
+ @crawler.router.default_handler
+ async def handler(context: BasicCrawlingContext) -> None:
+ started_urls.append(context.request.url)
+ if context.request.url == 'https://a.placeholder.com':
+ context.register_deferred_cleanup(cleanup)
+ raise RuntimeError('Arbitrary crash for testing purposes')
+
+ async def crash(_context: BasicCrawlingContext, _error: Exception) -> None:
+ raise RuntimeError('Crash in a user-defined handler')
+
+ getattr(crawler, crashing_hook)(crash)
+
+ with pytest.raises(UserDefinedErrorHandlerError):
+ await crawler.run([f'https://{name}.placeholder.com' for name in 'abcdef'])
+
+ cleanup.assert_awaited_once()
+ assert set(started_urls) <= {'https://a.placeholder.com', 'https://b.placeholder.com'}
+
+
+async def test_failed_run_rechecks_readiness() -> None:
+ """A run that fails while the request manager is asked for a ready request starts no new request."""
+ crawler = BasicCrawler(
+ configure_logging=False,
+ concurrency_settings=ConcurrencySettings(desired_concurrency=2, max_concurrency=2),
+ )
+ handler_calls = Mock()
+ cleanup_done = asyncio.Event()
+
+ async def set_cleanup_done() -> None:
+ cleanup_done.set()
+
+ @crawler.router.default_handler
+ async def handler(context: BasicCrawlingContext) -> None:
+ handler_calls()
+ context.register_deferred_cleanup(set_cleanup_done)
+ 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()
+ check_readiness = request_manager.check_readiness
+ readiness_calls = Mock()
+
+ async def gated_check_readiness() -> RequestSourceStatus:
+ readiness_calls()
+ # The first check lets the first request start, the next one returns once that request has failed the run.
+ if readiness_calls.call_count > 1:
+ await cleanup_done.wait()
+ return await check_readiness()
+
+ with (
+ patch.object(request_manager, 'check_readiness', side_effect=gated_check_readiness),
+ pytest.raises(UserDefinedErrorHandlerError),
+ ):
+ async with asyncio.timeout(10):
+ await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com'])
+
+ handler_calls.assert_called_once()
@pytest.mark.parametrize('handler', ['failed_request_handler', 'error_handler'])
@@ -702,22 +1181,6 @@ async def handler_implementation(context: BasicCrawlingContext, error: Exception
assert test_request == await rq.fetch_next_request()
-async def test_handles_error_in_failed_request_handler() -> None:
- crawler = BasicCrawler(max_request_retries=3)
-
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- if context.request.url == 'https://b.placeholder.com':
- 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')
-
- with pytest.raises(UserDefinedErrorHandlerError):
- await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
-
-
async def test_send_request_forwards_arguments_to_http_client() -> None:
"""Test that `context.send_request` passes all its arguments to the HTTP client."""
http_client = AsyncMock(spec=HttpClient, active=True)
@@ -3188,6 +3651,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:
@@ -3198,10 +3662,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:
@@ -3650,25 +4116,6 @@ async def test_unusable_bound_session_reaches_failed_request_handler() -> None:
assert context.session is session
-async def test_handles_session_error_in_failed_request_handler() -> None:
- crawler = BasicCrawler(max_request_retries=0)
- handler_requests = set()
-
- @crawler.router.default_handler
- async def handler(context: BasicCrawlingContext) -> None:
- raise SessionError('blocked')
-
- @crawler.failed_request_handler
- async def failed_request_handler(context: BasicCrawlingContext, error: Exception) -> None:
- handler_requests.add(context.request.url)
-
- requests = ['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com']
-
- await crawler.run(requests)
-
- assert set(requests) == handler_requests
-
-
async def test_reduced_logs_from_timed_out_request_handler(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO)
crawler = BasicCrawler(
@@ -4519,6 +4966,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',
[
@@ -5070,6 +5536,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..15402e2e1c 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
@@ -10,7 +11,12 @@
from crawlee import Request
from crawlee._types import BasicCrawlingContext
from crawlee.crawlers import ContextPipeline
-from crawlee.errors import ContextPipelineFinalizationError, ContextPipelineInitializationError, RequestHandlerError
+from crawlee.errors import (
+ ContextPipelineFinalizationError,
+ ContextPipelineInitializationError,
+ ContextPipelineInterruptedError,
+ RequestHandlerError,
+)
from crawlee.sessions._session import Session
if TYPE_CHECKING:
@@ -27,6 +33,10 @@ class MoreEnhancedCrawlingContext(EnhancedCrawlingContext):
bar: int
+class _CustomBaseError(BaseException):
+ """A `BaseException` that is neither an `Exception` nor a cancellation."""
+
+
async def test_calls_consumer_without_middleware() -> None:
consumer = AsyncMock()
@@ -176,19 +186,144 @@ async def step_2(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingC
assert cleanup.called
-async def test_handles_exceptions_in_middleware_finalization() -> None:
- consumer = AsyncMock()
+@pytest.mark.parametrize(
+ ('failure', 'expected_error'),
+ [
+ pytest.param('consumer', RequestHandlerError, id='consumer-error'),
+ pytest.param('initialization', ContextPipelineInitializationError, id='initialization-error'),
+ pytest.param('interruption', ContextPipelineInterruptedError, id='pipeline-interrupted'),
+ pytest.param('cancellation', asyncio.CancelledError, id='task-cancelled'),
+ pytest.param('cleanup', ContextPipelineFinalizationError, id='earlier-cleanup-error'),
+ pytest.param('later-cancellation', asyncio.CancelledError, id='later-cancellation'),
+ pytest.param('later-base-exception', _CustomBaseError, id='later-base-exception'),
+ ],
+)
+async def test_cleanup_error_keeps_first_error(
+ caplog: pytest.LogCaptureFixture, failure: str, expected_error: type[BaseException]
+) -> None:
+ """A cleanup error is only logged when an earlier error or a later cleanup's `BaseException` propagates."""
cleanup = AsyncMock()
+ cleanup_error = RuntimeError('Crash during middleware finalization')
async def step_1(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
yield context
await cleanup()
+ if failure == 'later-cancellation':
+ pipeline_task.cancel()
+ await asyncio.sleep(0)
+ if failure == 'later-base-exception':
+ raise _CustomBaseError
async def step_2(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
yield context
- raise RuntimeError('Crash during middleware finalization')
+ raise cleanup_error
- pipeline = ContextPipeline().compose(step_1).compose(step_2)
+ async def step_3(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
+ if failure == 'initialization':
+ raise RuntimeError('Crash during middleware initialization')
+ if failure == 'interruption':
+ raise ContextPipelineInterruptedError
+ yield context
+ if failure == 'cleanup':
+ raise RuntimeError('Earlier crash during middleware finalization')
+
+ async def consumer(_context: BasicCrawlingContext) -> None:
+ if failure == 'consumer':
+ raise RuntimeError('Crash in the consumer')
+ if failure == 'cancellation':
+ pipeline_task.cancel()
+ await asyncio.sleep(0)
+
+ pipeline = ContextPipeline().compose(step_1).compose(step_2).compose(step_3)
+ 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, consumer))
+
+ with pytest.raises(expected_error):
+ await pipeline_task
+
+ cleanup.assert_awaited_once()
+ [record] = caplog.records
+ assert record.levelno == logging.WARNING
+ assert record.exc_info
+ logged_error = record.exc_info[1]
+ assert isinstance(logged_error, ContextPipelineFinalizationError)
+ assert logged_error.wrapped_exception is cleanup_error
+
+
+@pytest.mark.parametrize(
+ 'violation',
+ [
+ pytest.param('interruption', id='pipeline-interrupted'),
+ pytest.param('second-yield', id='second-yield'),
+ ],
+)
+async def test_wraps_cleanup_protocol_errors(violation: str) -> None:
+ """A middleware that interrupts the pipeline or yields again in its cleanup fails as on any other cleanup error."""
+
+ async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
+ yield context
+ if violation == 'interruption':
+ raise ContextPipelineInterruptedError
+ 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(ContextPipelineFinalizationError) as exc_info:
+ await pipeline(context, AsyncMock())
+
+ assert isinstance(exc_info.value.wrapped_exception, RuntimeError)
+
+
+@pytest.mark.parametrize(
+ ('location', 'expected_error'),
+ [
+ pytest.param('consumer', RequestHandlerError, id='consumer'),
+ pytest.param('initialization', ContextPipelineInitializationError, id='middleware initialization'),
+ pytest.param('cleanup', ContextPipelineFinalizationError, id='middleware cleanup'),
+ ],
+)
+async def test_wraps_stray_cancelled_error(
+ *,
+ location: str,
+ expected_error: type[RequestHandlerError | ContextPipelineInitializationError | ContextPipelineFinalizationError],
+) -> None:
+ """A `CancelledError` raised while nothing cancels the task is wrapped like any other error."""
+ consumer = AsyncMock(side_effect=asyncio.CancelledError if location == 'consumer' else None)
+
+ async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]:
+ if location == 'initialization':
+ raise asyncio.CancelledError
+ yield context
+ if location == 'cleanup':
+ raise asyncio.CancelledError
+
+ pipeline = ContextPipeline().compose(step)
context = BasicCrawlingContext(
request=Request.from_url(url='https://test.io/'),
send_request=AsyncMock(),
@@ -203,8 +338,52 @@ async def step_2(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingC
extend_timeout=AsyncMock(),
)
- with pytest.raises(ContextPipelineFinalizationError):
+ with pytest.raises(expected_error) as exc_info:
await pipeline(context, consumer)
- assert consumer.called
- assert not cleanup.called
+ 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
diff --git a/tests/unit/crawlers/_http/test_http_crawler.py b/tests/unit/crawlers/_http/test_http_crawler.py
index d2ccfb793b..c92bd283dd 100644
--- a/tests/unit/crawlers/_http/test_http_crawler.py
+++ b/tests/unit/crawlers/_http/test_http_crawler.py
@@ -127,7 +127,7 @@ async def test_blocked_code_rotates_session(
],
)
async def test_non_blocked_code_fails(blocked_status_codes: list[int]) -> None:
- """Test that a 403 missing from `blocked_status_codes` fails the request as a client error."""
+ """Test that a 403 missing from `blocked_status_codes` fails the request without a retry as a client error."""
url = 'https://a.placeholder.com'
http_client = AsyncMock(spec=HttpClient, active=True)
http_client.send_request.return_value = mock_response(403, url)
@@ -140,6 +140,7 @@ async def test_non_blocked_code_fails(blocked_status_codes: list[int]) -> None:
await crawler.run([url])
handler.assert_not_called()
+ http_client.send_request.assert_awaited_once()
error = failed_request_handler.call_args.args[1]
assert isinstance(error, HttpClientStatusCodeError)