From 80b19f3407a10765a26481b42608ffee14a75b90 Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Wed, 2 Dec 2026 22:01:02 +0000 Subject: [PATCH] return interrupted requests to the request queue --- docs/06_upgrading/upgrading_to_v2.md | 2 +- src/crawlee/autoscaling/_autoscaled_pool.py | 7 + src/crawlee/crawlers/_basic/_basic_crawler.py | 29 +++- .../crawlers/_basic/_context_pipeline.py | 25 ++++ .../unit/autoscaling/test_autoscaled_pool.py | 28 +++- .../crawlers/_basic/test_basic_crawler.py | 137 ++++++++++++++++++ .../crawlers/_basic/test_context_pipeline.py | 85 +++++++++++ 7 files changed, 307 insertions(+), 6 deletions(-) diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index e0b980b763..fcfd9fde3b 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -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. 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..1aa9d85c2f 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 @@ -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 diff --git a/src/crawlee/crawlers/_basic/_context_pipeline.py b/src/crawlee/crawlers/_basic/_context_pipeline.py index f84d286d9f..8c51c92e11 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,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.""" @@ -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) @@ -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) 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..8069ebb63a 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -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]]() @@ -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( diff --git a/tests/unit/crawlers/_basic/test_context_pipeline.py b/tests/unit/crawlers/_basic/test_context_pipeline.py index ba13d21762..452167d516 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 @@ -208,3 +209,87 @@ async def step_2(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingC assert consumer.called assert not cleanup.called + + +@pytest.mark.parametrize( + ('in_middleware', 'expected_error'), + [ + pytest.param(False, RequestHandlerError, id='consumer'), + pytest.param(True, ContextPipelineInitializationError, id='middleware initialization'), + ], +) +async def test_wraps_stray_cancelled_error( + *, in_middleware: bool, expected_error: type[RequestHandlerError | ContextPipelineInitializationError] +) -> None: + """A `CancelledError` raised while nothing cancels the task is wrapped like any other error.""" + consumer = AsyncMock(side_effect=asyncio.CancelledError) + + async def step(context: BasicCrawlingContext) -> AsyncGenerator[BasicCrawlingContext, None]: + if in_middleware: + raise asyncio.CancelledError + 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(expected_error) as exc_info: + await pipeline(context, consumer) + + 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