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
57 changes: 47 additions & 10 deletions 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 @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.

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
2 changes: 1 addition & 1 deletion src/crawlee/crawlers/_basic/_crawler_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
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
Loading
Loading