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/02_requests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ApiLink to="class/NonRetryableError">`NonRetryableError`</ApiLink> fails the request without a retry and passes it to the failed request handler right away, without calling the error handler. A <ApiLink to="class/RetryRequestError">`RetryRequestError`</ApiLink> 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
Expand Down
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
2 changes: 1 addition & 1 deletion docs/03_concepts/08_pydantic_ai_crawler.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ApiLink to="class/NonRetryableError">`NonRetryableError`</ApiLink> to fail the request without a retry. To stop the crawl instead, set `abort_on_error=True`.
2 changes: 2 additions & 0 deletions docs/03_concepts/20_error_handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Here's how to turn off retries for non-network errors using <ApiLink to="class/B
{DisableRetry}
</RunnableCodeBlock>

When the request handler itself knows that another attempt won't help, it can raise a <ApiLink to="class/NonRetryableError">`NonRetryableError`</ApiLink> 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 <ApiLink to="class/Statistics">`Statistics`</ApiLink> 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 <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and [HTTP crawlers](./http-crawlers) capture the HTML file, but only <ApiLink to="class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> can capture a screenshot as well.
Expand Down
40 changes: 38 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,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.
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 `<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).

An error in a middleware cleanup 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. 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 <url>` 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.
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,
)
Loading
Loading