Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,14 @@ When the error handler sets `context.request.no_retry`, the request now fails ri

In the error handler, `context.request.retry_count` is the number of retries before the failed attempt. In v1, for errors other than `SessionError`, the crawler increased it before it called the error handler.

## A timeout in the error handling retries the request

The crawler gives the handling of a failed request `internal_timeout` to finish, which `context.extend_timeout()` extends. The handling covers the `error_handler`, the `failed_request_handler`, and giving the request back to the request manager or marking it as failed. When the time runs out for a request that can still be retried, the crawler now logs a warning and retries the request. The attempt counts towards `max_request_retries`, and a `SessionError` retires the session. When the time runs out in the `failed_request_handler`, the request stays failed, and the crawler logs a warning and goes on. In v1, both timeouts ended the crawl, and the handling of a `SessionError` had no time limit. Any other timeout for a request with no retries left, such as in marking it as failed, still ends the crawl.

## The crawler doesn't retry request manager or session pool calls

The crawler now makes one attempt at each call to its request manager and its session pool: fetching the next request, marking a request as handled, giving it back, and taking a session. Each call gets `internal_timeout` to finish, which now also covers giving back a request deferred by a `RequestThrottledError`. In v1, the crawler made up to 3 attempts at fetching a request, marking it as handled or taking a session when the call raised an error other than a timeout. The storage backends retry transient errors on their own, the same as in Crawlee JS. `SqlStorageBackend` and `RedisStorageBackend` make up to 3 attempts at a failed database call. A custom request manager, request queue backend or session pool that can fail for a moment, such as over the network, should retry such errors itself. Otherwise, a single error ends the crawl.

## `BasicCrawlingContext` requires `extend_timeout`

`BasicCrawlingContext` has a new required field, `extend_timeout`. If you build a crawling context yourself, such as in a test, pass it as well.
Expand Down Expand Up @@ -586,7 +594,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.

Expand Down Expand Up @@ -1401,6 +1409,10 @@ The per-minute rates of `StatisticsState`, `requests_succeeded_per_minute` and `

`StatisticsState.crawler_runtime_for_serialization` is removed, and the persisted `crawlerRuntimeMillis` value is a number of milliseconds instead of an ISO 8601 duration string. Read the runtime from the `crawler_runtime` property instead. Statistics persisted by v1 are still restored.

### A failed request is counted before the failed request handler runs

The crawler now counts a request as failed in its statistics before the `failed_request_handler` runs. In v1, it counted the failure after the handler, so a handler that raised left it uncounted.

### `persistence_enabled` no longer accepts `'explicit_only'`

`persistence_enabled` of `Statistics` no longer accepts `'explicit_only'`. Pass `True` or `False`. The value isn't validated, so `'explicit_only'` now acts as `True` and saves the statistics on every `PERSIST_STATE` event and on exit. In v1, it restored them but never saved them.
Expand Down Expand Up @@ -1592,6 +1604,10 @@ Each dataset logs the warning about unsupported arguments once for each set of a

`RequestQueue.purge()` no longer logs the `Storage client "..." does not support purging the request queue.` warnings. It raises `NotImplementedError` instead. For details, see [`RequestQueue.purge` raises when the storage backend can't purge](#requestqueuepurge-raises-when-the-storage-backend-cant-purge).

The WARNING `<error>: retrying (<attempt>/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 <url> due to: <error>` and retries the request. When the `failed_request_handler` times out, the crawler logs the WARNING `The failed request handler of <url> was cancelled: <error>`. In v1, the crawler logged the ERROR `An exception occurred during handling of failed request. This places the crawler and its underlying storages into an unknown state and crawling will be terminated.` and ended the crawl. For details, see [A timeout in the error handling retries the request](#a-timeout-in-the-error-handling-retries-the-request).

A cancelled `run()` doesn't log `Final request statistics` or `Error analysis`. For details, see [A timeout or cancellation around `run()` raises](#a-timeout-or-cancellation-around-run-raises).

The storage backends no longer log the `Failed to decode JSON value for key "..."` and `Failed to decode text value for key "..."` warnings. Instead, `KeyValueStore` raises `ValueError` for a record that isn't valid JSON, and replaces the bytes it can't decode in a text or JSON record. For details, see [Reading values](#reading-values). `RedisStorageBackend` no longer logs the `Metadata for key "..." is missing or invalid.` warning when it reads a key that has no record.
Expand Down
1 change: 0 additions & 1 deletion src/crawlee/_utils/recoverable_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
35 changes: 13 additions & 22 deletions src/crawlee/_utils/wait.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 7 additions & 0 deletions src/crawlee/autoscaling/_autoscaled_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading