Skip to content
Open
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: 1 addition & 1 deletion docs/06_upgrading/upgrading_to_v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ async def main() -> None:

### A timeout or cancellation around `run()` raises

In v1, `crawler.run()` caught the cancellation of the task that awaited it and returned the final statistics. A timeout around `run()`, such as `asyncio.wait_for()` or `asyncio.timeout()`, that expired during the crawl didn't raise `TimeoutError`, and a task running `run()` returned the statistics even after `task.cancel()`. In v2, `run()` lets the requests in progress finish and then raises `CancelledError`, which a timeout turns into `TimeoutError`. Each further cancellation cancels one of the requests in progress, so an anyio cancel scope, which keeps sending it, cancels them all. A cancelled run doesn't log the final statistics or the error analysis, the same as a failed run. Ctrl+C still ends the crawl gracefully and returns the statistics.
In v1, `crawler.run()` caught the cancellation of the task that awaited it and returned the final statistics. A timeout around `run()`, such as `asyncio.wait_for()` or `asyncio.timeout()`, that expired during the crawl didn't raise `TimeoutError`, and a task running `run()` returned the statistics even after `task.cancel()`. In v2, `run()` lets the requests in progress finish and then raises `CancelledError`, which a timeout turns into `TimeoutError`. Each further cancellation cancels one of the requests in progress, so an anyio cancel scope, which keeps sending it, cancels them all. A cancelled request goes back to the request manager, and the next `run()` processes it again. A cancelled run doesn't log the final statistics or the error analysis, the same as a failed run. Ctrl+C still ends the crawl gracefully and returns the statistics.

To limit how long a crawl runs and still get the statistics, stop the crawler when the time is up. The requests in progress still finish, so the crawl can end after the limit.

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
29 changes: 28 additions & 1 deletion src/crawlee/crawlers/_basic/_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1719,6 +1719,33 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002
if request is None:
return

try:
await self.__process_request(request)
except BaseException:
# A request left in progress would hold up any later `run()` on the same request manager. A request marked
# as handled isn't reclaimed, since some request managers, such as the Apify platform queue, would process
# it again. The reclaim runs as a task, since anyio cancel scopes keep cancelling every await.
if not request.was_already_handled:
reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request_manager, request))
while not reclaim.done():
with suppress(CancelledError):
await asyncio.shield(reclaim)
raise

async def __reclaim_request_after_failure(self, request_manager: RequestManager, request: Request) -> None:
try:
await wait_for(
lambda: request_manager.reclaim_request(request),
timeout=self._internal_timeout,
timeout_message=f'Reclaiming request timed out after {self._internal_timeout.total_seconds()} seconds',
logger=self._logger,
)
except (Exception, CancelledError):
# The caller awaits this task through a shield, so only the reclaim itself or the shutdown of the event loop
# can raise a `CancelledError` here. The original exception is raised anyway, so this one is only logged.
self._logger.warning('Failed to reclaim the unfinished request %s', request.url, exc_info=True)

async def __process_request(self, request: Request) -> None:
if not (await self._is_allowed_based_on_robots_txt_file(request.url)):
self._logger.warning(
'Skipping request %s (%s) because it is disallowed based on robots.txt', request.url, request.unique_key
Expand Down
25 changes: 25 additions & 0 deletions src/crawlee/crawlers/_basic/_context_pipeline.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Any, Generic, cast

from typing_extensions import TypeVar
Expand All @@ -20,6 +21,21 @@
TMiddlewareCrawlingContext = TypeVar('TMiddlewareCrawlingContext', bound=BasicCrawlingContext)


def _as_error_unless_cancelled(exc: asyncio.CancelledError) -> RuntimeError | None:
"""Turn a `CancelledError` that no cancellation of the current task explains into an ordinary error.

Code raises one when it awaits a future that something else cancelled, and the request is then retried and failed
like on any other error. Returns `None` when the task is being cancelled.
"""
task = asyncio.current_task()
if task is None or task.cancelling() > 0:
return None

error = RuntimeError('`CancelledError` was raised, although nothing cancelled the task')
error.__cause__ = exc
return error


class _Middleware(Generic[TMiddlewareCrawlingContext, TCrawlingContext]):
"""Helper wrapper class to make the middleware easily observable by open telemetry instrumentation."""

Expand Down Expand Up @@ -103,6 +119,10 @@ async def __call__(
raise
except Exception as e:
raise ContextPipelineInitializationError(e, crawling_context) from e
except asyncio.CancelledError as e:
if (error := _as_error_unless_cancelled(e)) is None:
raise
raise ContextPipelineInitializationError(error, crawling_context) from error

crawling_context = result
cleanup_stack.append(middleware_instance)
Expand All @@ -112,6 +132,11 @@ async def __call__(
except Exception as e:
final_consumer_exception = e
raise RequestHandlerError(e, crawling_context) from e
except asyncio.CancelledError as e:
if (error := _as_error_unless_cancelled(e)) is None:
raise
final_consumer_exception = error
raise RequestHandlerError(error, crawling_context) from error
finally:
for middleware_instance in reversed(cleanup_stack):
await middleware_instance.cleanup(final_consumer_exception)
Expand Down
28 changes: 24 additions & 4 deletions tests/unit/autoscaling/test_autoscaled_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()


Expand Down
137 changes: 137 additions & 0 deletions tests/unit/crawlers/_basic/test_basic_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,109 @@ async def error_handler(context: BasicCrawlingContext, error: Exception) -> None
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])


async def test_error_handler_crash_reclaims_request() -> None:
"""A request whose error handler raised goes back to the request manager."""
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')

with pytest.raises(UserDefinedErrorHandlerError):
await crawler.run(['https://a.placeholder.com'])

request_manager = await crawler.get_request_manager()
request = await request_manager.fetch_next_request()
assert request is not None


async def test_handled_request_skips_reclaim() -> None:
"""A request already marked as handled isn't reclaimed when its failed request handler raises."""
crawler = BasicCrawler(configure_logging=False, max_request_retries=0)

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
raise RuntimeError('Arbitrary crash for testing purposes')

@crawler.failed_request_handler
async def failed_request_handler(_context: BasicCrawlingContext, _error: Exception) -> None:
raise RuntimeError('Crash in failed request handler')

request_manager = await crawler.get_request_manager()

with (
patch.object(request_manager, 'reclaim_request', wraps=request_manager.reclaim_request) as reclaim_mock,
pytest.raises(UserDefinedErrorHandlerError),
):
await crawler.run(['https://a.placeholder.com'])

reclaim_mock.assert_not_awaited()


@pytest.mark.parametrize(
'reclaim_error',
[
pytest.param(RuntimeError('Reclaim failed'), id='error'),
pytest.param(asyncio.CancelledError(), id='cancelled-error'),
],
)
async def test_failed_reclaim_after_crash_logged(
caplog: pytest.LogCaptureFixture, reclaim_error: BaseException
) -> None:
"""A reclaim that fails after the processing of a request failed logs a warning."""
crawler = BasicCrawler(configure_logging=False)

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
raise RuntimeError('Arbitrary crash for testing purposes')

@crawler.error_handler
async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None:
raise RuntimeError('Crash in error handler')

request_manager = await crawler.get_request_manager()

with (
patch.object(request_manager, 'reclaim_request', side_effect=reclaim_error),
pytest.raises(UserDefinedErrorHandlerError),
):
await crawler.run(['https://a.placeholder.com'])

warnings = [
record
for record in caplog.records
if record.levelno == logging.WARNING and 'Failed to reclaim the unfinished request' in record.message
]
assert len(warnings) == 1
assert warnings[0].exc_info is not None


async def test_handler_cancelled_error_fails_request() -> None:
"""A `CancelledError` that the request handler raises itself is retried and then fails the request."""
crawler = BasicCrawler(configure_logging=False, max_request_retries=1)
handler_calls = Mock()
failed_errors = list[Exception]()

@crawler.router.default_handler
async def handler(_context: BasicCrawlingContext) -> None:
handler_calls()
raise asyncio.CancelledError

@crawler.failed_request_handler
async def failed_request_handler(_context: BasicCrawlingContext, error: Exception) -> None:
failed_errors.append(error)

await crawler.run(['https://a.placeholder.com'])

assert handler_calls.call_count == 2
assert len(failed_errors) == 1
assert isinstance(failed_errors[0].__cause__, asyncio.CancelledError)


async def test_calls_failed_request_handler() -> None:
crawler = BasicCrawler(max_request_retries=3)
calls = list[tuple[BasicCrawlingContext, Exception]]()
Expand Down Expand Up @@ -5070,6 +5173,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(
Expand Down
Loading
Loading