From 17f517bbedf578aca0147e1dd105a434016c1a8a Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Wed, 2 Dec 2026 22:01:02 +0000 Subject: [PATCH 1/2] 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 | 57 ++++- .../crawlers/_basic/_context_pipeline.py | 25 ++ src/crawlee/crawlers/_basic/_crawler_run.py | 2 +- .../unit/autoscaling/test_autoscaled_pool.py | 28 +- .../crawlers/_basic/test_basic_crawler.py | 242 ++++++++++++++++++ .../crawlers/_basic/test_context_pipeline.py | 85 ++++++ 8 files changed, 432 insertions(+), 16 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..865964dc88 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 @@ -1699,6 +1699,10 @@ async def __is_task_ready_function(self) -> bool: request_manager = await self.get_request_manager() readiness = await request_manager.check_readiness() + # The run can fail while the request manager is being asked. + if self._run.failed: + return False + # Without a wake-up, a paced crawl would resume only at the pool's next poll. if readiness.status == 'waiting' and readiness.ready_at is not None: self._run.schedule_wake(readiness.ready_at) @@ -1719,6 +1723,48 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 if request is None: return + deferred_cleanup: list[Callable[[], Awaitable[None]]] = [] + + try: + await self.__process_request(request, deferred_cleanup) + except BaseException: + # The error ends the run. Failing it first keeps the pool from starting new requests while the reclaim and + # the deferred cleanups, such as closing a page, still run. A task that is being cancelled doesn't end the + # run, so it doesn't fail it. + current_task = asyncio.current_task() + if current_task is not None and current_task.cancelling() == 0: + self._run.fail() + + # 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 + finally: + for cleanup in deferred_cleanup: + try: + await cleanup() + except Exception: + self._logger.exception('Error in deferred cleanup') + + 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, deferred_cleanup: list[Callable[[], Awaitable[None]]]) -> 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 @@ -1746,8 +1792,6 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 proxy_info = session.proxy_info result = RequestHandlerRunResult(key_value_store_getter=self.get_key_value_store) - deferred_cleanup: list[Callable[[], Awaitable[None]]] = [] - context = BasicCrawlingContext( request=request, session=session, @@ -1835,13 +1879,6 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 ) raise - finally: - for cleanup in deferred_cleanup: - try: - await cleanup() - except Exception: - self._logger.exception('Error in deferred cleanup') - async def _report_rate_limit(self, request: Request, error: RequestThrottledError) -> bool: """Report a rate limit for the request's URL and check whether the request manager took responsibility for it. 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/src/crawlee/crawlers/_basic/_crawler_run.py b/src/crawlee/crawlers/_basic/_crawler_run.py index 610b3a1023..b6b8752950 100644 --- a/src/crawlee/crawlers/_basic/_crawler_run.py +++ b/src/crawlee/crawlers/_basic/_crawler_run.py @@ -81,7 +81,7 @@ def stop_requested(self) -> bool: @property def failed(self) -> bool: - """Whether a request has failed while the crawler aborts on an error.""" + """Whether the run has failed, so that it takes no new requests.""" return self._failed async def dispatch_requests(self) -> None: 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..d97d090f2a 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -642,6 +642,214 @@ 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 is reclaimed, and the failing run doesn't process it again.""" + crawler = BasicCrawler(configure_logging=False) + handler_calls = Mock() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_calls() + 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 + handler_calls.assert_called_once() + + +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_cancelled_task_keeps_run_going() -> None: + """A request whose task was cancelled while the run goes on is reclaimed and handled in the same run.""" + crawler = BasicCrawler(configure_logging=False) + handler_calls = Mock() + + @crawler.router.default_handler + async def handler(_context: BasicCrawlingContext) -> None: + handler_calls() + if handler_calls.call_count == 1: + task = asyncio.current_task() + assert task is not None + task.cancel() + await asyncio.sleep(0) + + stats = await crawler.run(['https://a.placeholder.com']) + + assert stats.requests_succeeded == 1 + + +@pytest.mark.parametrize( + ('max_request_retries', 'crashing_hook'), + [ + pytest.param(1, 'error_handler', id='unhandled-request'), + pytest.param(0, 'failed_request_handler', id='handled-request'), + ], +) +async def test_failed_run_starts_no_new_request(max_request_retries: int, crashing_hook: str) -> None: + """An error that ends the run starts no new request while the deferred cleanup of the failed one still runs.""" + crawler = BasicCrawler( + configure_logging=False, + max_request_retries=max_request_retries, + concurrency_settings=ConcurrencySettings(desired_concurrency=2, max_concurrency=2), + ) + started_urls = list[str]() + + async def close_page() -> None: + await asyncio.sleep(0.5) + + cleanup = AsyncMock(side_effect=close_page) + + @crawler.router.default_handler + async def handler(context: BasicCrawlingContext) -> None: + started_urls.append(context.request.url) + if context.request.url == 'https://a.placeholder.com': + context.register_deferred_cleanup(cleanup) + raise RuntimeError('Arbitrary crash for testing purposes') + + async def crash(_context: BasicCrawlingContext, _error: Exception) -> None: + raise RuntimeError('Crash in a user-defined handler') + + getattr(crawler, crashing_hook)(crash) + + with pytest.raises(UserDefinedErrorHandlerError): + await crawler.run([f'https://{name}.placeholder.com' for name in 'abcdef']) + + cleanup.assert_awaited_once() + assert set(started_urls) <= {'https://a.placeholder.com', 'https://b.placeholder.com'} + + +async def test_failed_run_rechecks_readiness() -> None: + """A run that fails while the request manager is asked for a ready request starts no new request.""" + crawler = BasicCrawler( + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=2, max_concurrency=2), + ) + handler_calls = Mock() + cleanup_done = asyncio.Event() + + async def set_cleanup_done() -> None: + cleanup_done.set() + + @crawler.router.default_handler + async def handler(context: BasicCrawlingContext) -> None: + handler_calls() + context.register_deferred_cleanup(set_cleanup_done) + 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() + check_readiness = request_manager.check_readiness + readiness_calls = Mock() + + async def gated_check_readiness() -> RequestSourceStatus: + readiness_calls() + # The first check lets the first request start, the next one returns once that request has failed the run. + if readiness_calls.call_count > 1: + await cleanup_done.wait() + return await check_readiness() + + with ( + patch.object(request_manager, 'check_readiness', side_effect=gated_check_readiness), + pytest.raises(UserDefinedErrorHandlerError), + ): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com']) + + handler_calls.assert_called_once() + + async def test_calls_failed_request_handler() -> None: crawler = BasicCrawler(max_request_retries=3) calls = list[tuple[BasicCrawlingContext, Exception]]() @@ -5070,6 +5278,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 From 51f63d3ce06e3768adb31cf5897fb202e58c75aa Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Thu, 3 Dec 2026 15:02:36 +0000 Subject: [PATCH 2/2] leave retrying request manager calls to the backends --- docs/06_upgrading/upgrading_to_v2.md | 16 ++ src/crawlee/_utils/recoverable_state.py | 1 - src/crawlee/_utils/wait.py | 35 ++- src/crawlee/crawlers/_basic/_basic_crawler.py | 71 ++++--- tests/unit/_utils/test_wait.py | 24 ++- .../crawlers/_basic/test_basic_crawler.py | 199 +++++++++++++++++- 6 files changed, 292 insertions(+), 54 deletions(-) diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index fcfd9fde3b..d0d7f4e904 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -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. @@ -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. @@ -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 `: retrying (/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 due to: ` and retries the request. When the `failed_request_handler` times out, the crawler logs the WARNING `The failed request handler of was cancelled: `. 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. diff --git a/src/crawlee/_utils/recoverable_state.py b/src/crawlee/_utils/recoverable_state.py index 4ca9d0e52a..531145bc8d 100644 --- a/src/crawlee/_utils/recoverable_state.py +++ b/src/crawlee/_utils/recoverable_state.py @@ -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, ) diff --git a/src/crawlee/_utils/wait.py b/src/crawlee/_utils/wait.py index 3a39d4853d..6596ccb577 100644 --- a/src/crawlee/_utils/wait.py +++ b/src/crawlee/_utils/wait.py @@ -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( diff --git a/src/crawlee/crawlers/_basic/_basic_crawler.py b/src/crawlee/crawlers/_basic/_basic_crawler.py index 865964dc88..a3496319db 100644 --- a/src/crawlee/crawlers/_basic/_basic_crawler.py +++ b/src/crawlee/crawlers/_basic/_basic_crawler.py @@ -734,8 +734,6 @@ async def _get_session(self) -> Session: timeout=self._internal_timeout, timeout_message='Fetching a session from the pool timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - max_retries=3, - logger=self._logger, ) async def _get_session_by_id(self, session_id: str) -> Session | None: @@ -745,8 +743,6 @@ async def _get_session_by_id(self, session_id: str) -> Session | None: timeout=self._internal_timeout, timeout_message='Fetching a session from the pool timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - max_retries=3, - logger=self._logger, ) async def get_request_manager(self) -> RequestManager: @@ -1398,7 +1394,6 @@ async def _handle_request_retries( context: TCrawlingContext | BasicCrawlingContext, error: Exception, ) -> None: - request_manager = await self.get_request_manager() request = context.request # The session is retired before the request goes back to the queue, so that its retry can't get the same one. retire_session = isinstance(error, SessionError) @@ -1424,27 +1419,49 @@ async def _handle_request_retries( ) if retire_session: context.session.retire() - await request_manager.reclaim_request(request) + await self._reclaim_request(request) return if retire_session: context.session.retire() request.state = RequestState.ERROR await self._mark_request_as_handled(request) - await self._handle_failed_request(context, error) self._statistics.record_request_processing_failure(request.unique_key) + await self._handle_failed_request(context, error) async def _handle_request_error(self, context: TCrawlingContext | BasicCrawlingContext, error: Exception) -> None: + request = context.request + retry_count_before = request.retry_count + can_retry = self._should_retry_request(context, error) try: context.request.state = RequestState.ERROR_HANDLER - await wait_for_extendable( - partial(self._handle_request_retries, context, error), - timeout=self._internal_timeout, - timeout_message=lambda timeout: ( - f'Handling request failure timed out after {timeout.total_seconds()} seconds' - ), - ) + try: + await wait_for_extendable( + partial(self._handle_request_retries, context, error), + timeout=self._internal_timeout, + timeout_message=lambda timeout: ( + f'Handling request failure timed out after {timeout.total_seconds()} seconds' + ), + ) + except TimeoutError as timeout_error: + request.state = RequestState.ERROR + # A request that has already failed keeps its failure. One that can still be retried is retried, and + # the retry is counted, so that an error handler that always times out can't retry it forever. Any + # other timeout ends the crawl, as any other error here does. + if request.was_already_handled: + self._logger.warning( + 'The failed request handler of %s was cancelled: %s', request.url, timeout_error + ) + elif can_retry: + self._logger.warning('Retrying request to %s due to: %s', request.url, timeout_error) + if request.retry_count == retry_count_before: + request.retry_count += 1 + if isinstance(error, SessionError): + context.session.retire() + await self._reclaim_request(request) + else: + raise except UserDefinedErrorHandlerError: context.request.state = RequestState.ERROR raise @@ -1716,8 +1733,6 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 request_manager.fetch_next_request, timeout=self._internal_timeout, timeout_message=f'Fetching next request failed after {self._internal_timeout.total_seconds()} seconds', - logger=self._logger, - max_retries=3, ) if request is None: @@ -1739,7 +1754,7 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 # 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)) + reclaim = asyncio.create_task(self.__reclaim_request_after_failure(request)) while not reclaim.done(): with suppress(CancelledError): await asyncio.shield(reclaim) @@ -1751,14 +1766,9 @@ async def __run_task_function(self, task_id: str) -> None: # noqa: ARG002 except Exception: self._logger.exception('Error in deferred cleanup') - async def __reclaim_request_after_failure(self, request_manager: RequestManager, request: Request) -> None: + async def __reclaim_request_after_failure(self, 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, - ) + await self._reclaim_request(request) 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. @@ -1925,8 +1935,7 @@ async def _defer_throttled_request(self, request: Request, error: RequestThrottl self._logger.debug( 'Deferring request because its domain is rate-limiting us. %s', error, extra=request_log_extra(request) ) - request_manager = await self.get_request_manager() - await request_manager.reclaim_request(request, forefront=True) + await self._reclaim_request(request, forefront=True) self._statistics.record_request_processing_deferral(request.unique_key) async def _run_request_handler(self, context: BasicCrawlingContext) -> None: @@ -2212,7 +2221,13 @@ async def _mark_request_as_handled(self, request: Request) -> None: timeout=self._internal_timeout, timeout_message='Marking request as handled timed out after ' f'{self._internal_timeout.total_seconds()} seconds', - logger=self._logger, - max_retries=3, ) self._run.handled_request = True + + async def _reclaim_request(self, request: Request, *, forefront: bool = False) -> None: + request_manager = await self.get_request_manager() + await wait_for( + lambda: request_manager.reclaim_request(request, forefront=forefront), + timeout=self._internal_timeout, + timeout_message=f'Reclaiming request timed out after {self._internal_timeout.total_seconds()} seconds', + ) diff --git a/tests/unit/_utils/test_wait.py b/tests/unit/_utils/test_wait.py index 65c6af6ca4..1ec61b685b 100644 --- a/tests/unit/_utils/test_wait.py +++ b/tests/unit/_utils/test_wait.py @@ -3,8 +3,15 @@ import asyncio import logging from datetime import timedelta +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock -from crawlee._utils.wait import wait_for_all_tasks_to_finish +import pytest + +from crawlee._utils.wait import wait_for, wait_for_all_tasks_to_finish + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable async def test_zero_timeout_cancels_right_away() -> None: @@ -18,3 +25,18 @@ async def test_zero_timeout_cancels_right_away() -> None: ) assert task.cancelled() + + +@pytest.mark.parametrize( + ('operation', 'message'), + [ + pytest.param(lambda: asyncio.Event().wait(), 'Internal timeout', id='timeout-expired'), + pytest.param( + AsyncMock(side_effect=TimeoutError('Driver timed out')), 'Driver timed out', id='operation-timeout' + ), + ], +) +async def test_wait_for_timeout_message(operation: Callable[[], Awaitable[object]], message: str) -> None: + """The `timeout_message` replaces only the message of a timeout that `wait_for` raises itself.""" + with pytest.raises(TimeoutError, match=message): + await wait_for(operation, timeout=timedelta(seconds=0.05), timeout_message='Internal timeout') diff --git a/tests/unit/crawlers/_basic/test_basic_crawler.py b/tests/unit/crawlers/_basic/test_basic_crawler.py index d97d090f2a..3be7c29b4a 100644 --- a/tests/unit/crawlers/_basic/test_basic_crawler.py +++ b/tests/unit/crawlers/_basic/test_basic_crawler.py @@ -623,7 +623,7 @@ async def handler(_context: BasicCrawlingContext) -> None: with patch.object(queue, 'reclaim_request', wraps=queue.reclaim_request) as reclaim_mock: await crawler.run(['https://a.placeholder.com']) - reclaim_mock.assert_awaited_once_with(ANY) + reclaim_mock.assert_awaited_once_with(ANY, forefront=False) async def test_handles_error_in_error_handler() -> None: @@ -666,7 +666,7 @@ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> No async def test_handled_request_skips_reclaim() -> None: - """A request already marked as handled isn't reclaimed when its failed request handler raises.""" + """A failed request is counted and isn't reclaimed when its failed request handler raises.""" crawler = BasicCrawler(configure_logging=False, max_request_retries=0) @crawler.router.default_handler @@ -685,6 +685,7 @@ async def failed_request_handler(_context: BasicCrawlingContext, _error: Excepti ): await crawler.run(['https://a.placeholder.com']) + assert crawler.statistics.state.requests_failed == 1 reclaim_mock.assert_not_awaited() @@ -726,6 +727,178 @@ async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> No assert warnings[0].exc_info is not None +@pytest.mark.parametrize( + ('owner', 'method'), + [ + pytest.param('request_manager', 'fetch_next_request', id='fetch'), + pytest.param('request_manager', 'mark_request_as_handled', id='mark'), + pytest.param('session_pool', 'get_session', id='session'), + ], +) +async def test_failed_internal_call_not_retried(owner: str, method: str) -> None: + """A failing call to the request manager or the session pool ends the run without another attempt.""" + async with SessionPool() as session_pool: + crawler = BasicCrawler( + session_pool=session_pool, + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + request_handler=AsyncMock(), + ) + owners = {'request_manager': await crawler.get_request_manager(), 'session_pool': session_pool} + + with ( + patch.object(owners[owner], method, side_effect=RuntimeError('Internal call failed')) as call_mock, + pytest.raises(RuntimeError, match='Internal call failed'), + ): + await crawler.run(['https://a.placeholder.com']) + + assert call_mock.await_count == 1 + + +@pytest.mark.parametrize( + ('error', 'session_retired'), + [ + pytest.param(RuntimeError('Arbitrary crash for testing purposes'), False, id='error'), + pytest.param(SessionError('blocked'), True, id='session-error'), + ], +) +async def test_failure_timeout_retries_request( + caplog: pytest.LogCaptureFixture, error: Exception, *, session_retired: bool +) -> None: + """A request whose failure handling times out is retried and counted, and a session error retires its session.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=2, + ) + sessions = list[Session]() + observe = Mock() + + @crawler.router.default_handler + async def handler(context: BasicCrawlingContext) -> None: + sessions.append(context.session) + raise error + + @crawler.error_handler + async def error_handler(context: BasicCrawlingContext, _error: Exception) -> None: + observe(retry_count=context.request.retry_count, retired=sessions[0].retired) + if context.request.retry_count == 0: + await asyncio.Event().wait() + + with caplog.at_level(logging.WARNING, logger='crawlee'): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + messages = [record.getMessage() for record in caplog.records] + expected_warning = ( + 'Retrying request to https://a.placeholder.com due to: Handling request failure timed out after 1.0 seconds' + ) + assert messages.count(expected_warning) == 1 + assert observe.call_args_list == [call(retry_count=0, retired=False), call(retry_count=1, retired=session_retired)] + + +async def test_failure_timeout_counts_one_retry() -> None: + """A timeout after the retry was counted retries the request without counting it again.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=1, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + failed_request_handler = AsyncMock() + crawler.failed_request_handler(failed_request_handler) + request_manager = await crawler.get_request_manager() + reclaim_request = request_manager.reclaim_request + + async def reclaim_after_first_hang(request: Request, **kwargs: Any) -> ProcessedRequest | None: + if reclaim_mock.await_count == 1: + await asyncio.Event().wait() + return await reclaim_request(request, **kwargs) + + with patch.object(request_manager, 'reclaim_request', side_effect=reclaim_after_first_hang) as reclaim_mock: + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + context = failed_request_handler.call_args.args[0] + assert context.request.retry_count == 1 + + +async def test_failure_timeout_reclaim_fails() -> None: + """A reclaim that fails after a timed-out failure handling ends the crawl.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=1, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + + @crawler.error_handler + async def error_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + await asyncio.Event().wait() + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', side_effect=RuntimeError('Reclaim failed')), + pytest.raises(RuntimeError, match='Reclaim failed'), + ): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + +async def test_final_failure_timeout_ends_crawl() -> None: + """A failure handling that times out for a request with no retries left ends the crawl.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + max_request_retries=0, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + request_manager = await crawler.get_request_manager() + + async def hanging_mark(_request: Request) -> None: + await asyncio.Event().wait() + + with ( + patch.object(request_manager, 'mark_request_as_handled', side_effect=hanging_mark), + pytest.raises(TimeoutError, match='Handling request failure timed out'), + ): + async with asyncio.timeout(10): + await crawler.run(['https://a.placeholder.com']) + + +async def test_failed_handler_timeout_warns(caplog: pytest.LogCaptureFixture) -> None: + """A failed request handler that times out logs a warning, the request stays failed, and the crawl goes on.""" + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1), + max_request_retries=0, + request_handler=AsyncMock(side_effect=RuntimeError('Arbitrary crash for testing purposes')), + ) + + @crawler.failed_request_handler + async def failed_request_handler(_context: BasicCrawlingContext, _error: Exception) -> None: + await asyncio.Event().wait() + + request_manager = await crawler.get_request_manager() + + with ( + patch.object(request_manager, 'reclaim_request', wraps=request_manager.reclaim_request) as reclaim_mock, + caplog.at_level(logging.WARNING, logger='crawlee'), + ): + stats = await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com']) + + messages = [record.getMessage() for record in caplog.records] + expected_warning = ( + 'The failed request handler of https://a.placeholder.com was cancelled: ' + 'Handling request failure timed out after 1.0 seconds' + ) + assert messages.count(expected_warning) == 1 + assert stats.requests_failed == 2 + reclaim_mock.assert_not_awaited() + + 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) @@ -3396,6 +3569,7 @@ async def test_error_handler_extends_timeout() -> None: configuration=Configuration(internal_timeout=timedelta(seconds=1)), max_request_retries=1, ) + error_handler_finished = Mock() @crawler.router.default_handler async def handler(context: BasicCrawlingContext) -> None: @@ -3406,10 +3580,12 @@ async def handler(context: BasicCrawlingContext) -> None: async def error_handler(context: BasicCrawlingContext, _error: Exception) -> None: await context.extend_timeout(timedelta(seconds=10)) await asyncio.sleep(1.5) + error_handler_finished() stats = await crawler.run(['https://a.placeholder.com']) assert stats.requests_succeeded == 1 + error_handler_finished.assert_called_once() async def test_extend_timeout_extends_lock() -> None: @@ -4727,6 +4903,25 @@ async def handler(context: BasicCrawlingContext) -> None: reclaim_mock.assert_awaited_once_with(ANY, forefront=True) +async def test_deferred_reclaim_times_out(monkeypatch: pytest.MonkeyPatch) -> None: + """A reclaim of a deferred request that hangs times out after the internal timeout.""" + throttler = await open_throttler() + + async def hanging_reclaim(*_args: Any, **_kwargs: Any) -> None: + await asyncio.Event().wait() + + monkeypatch.setattr(throttler, 'reclaim_request', hanging_reclaim) + crawler = BasicCrawler( + configuration=Configuration(internal_timeout=timedelta(seconds=1)), + configure_logging=False, + request_manager=throttler, + request_handler=AsyncMock(side_effect=RequestThrottledError), + ) + + with pytest.raises(TimeoutError, match='Reclaiming request timed out'): + await crawler.run([THROTTLED_URL]) + + @pytest.mark.parametrize( 'use_throttler', [