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
2 changes: 2 additions & 0 deletions docs/03_concepts/03_crawling_context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ The example simulates a failure on the first attempt. The dataset ends up with a
{BufferedResultsExample}
</RunnableCodeBlock>

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.
Expand Down
32 changes: 30 additions & 2 deletions docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,24 @@ 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.

## `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 +604,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 @@ -854,7 +872,7 @@ async def main() -> None:
await crawler.run(['https://crawlee.dev/'])
```

A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. A `context.send_request` call there goes without a proxy.
A request bound by `session_id` to a session that's no longer in the pool gets a retired session without a proxy in its failed request handler. So does a request for which taking a session failed, in its `error_handler` and `failed_request_handler`. A `context.send_request` call there goes without a proxy.

### `create_session_function` gets the session options

Expand Down Expand Up @@ -1401,6 +1419,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 +1614,12 @@ 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).

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 <url> due to: <error>`, or to the ERROR `Request to <url> 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> seconds`. For details, see [An error in taking a session or storing the results retries the request](#an-error-in-taking-a-session-or-storing-the-results-retries-the-request).

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

The storage backends no longer log the `Failed to decode JSON value for key "..."` and `Failed to decode text value for key "..."` warnings. Instead, `KeyValueStore` raises `ValueError` for a record that isn't valid JSON, and replaces the bytes it can't decode in a text or JSON record. For details, see [Reading values](#reading-values). `RedisStorageBackend` no longer logs the `Metadata for key "..." is missing or invalid.` warning when it reads a key that has no record.
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