Scrapy, a fast high-level web crawling & scraping framework for Python.
Make closing the spider stop the engine, other state transition fixes (#8217)
Andrey Rakhmatullinbb1b5c6785e1
diff --git a/docs/news.rst b/docs/news.rstindex a91aef497..b673ca788 100644--- a/docs/news.rst+++ b/docs/news.rst@@ -22,6 +22,48 @@ Backward-incompatible changes``errback`` are no longer called, and a warning is issued if they areset.+ (:gh:`8176`)++- Changes to the behavior of :class:`~scrapy.core.engine.ExecutionEngine`+ methods that change its state:++ - :meth:`~scrapy.core.engine.ExecutionEngine.close_spider_async` now also+ stops the engine. Calling it while the spider is closing now completes+ immediately instead of waiting for the in-flight requests, and calling it+ after the spider has been closed no longer raises :exc:`RuntimeError`.++ - :meth:`~scrapy.core.engine.ExecutionEngine.stop_async` now just calls+ :meth:`~scrapy.core.engine.ExecutionEngine.close_spider_async` with the+ ``shutdown`` reason. Calling it after+ :meth:`~scrapy.core.engine.ExecutionEngine.open_spider_async` and before+ :meth:`~scrapy.core.engine.ExecutionEngine.start_async` now closes the+ spider instead of raising :exc:`RuntimeError`. Calling it while the+ spider is closing or after the engine has stopped now completes+ immediately, instead of raising :exc:`RuntimeError` or waiting for the+ in-flight requests.++ - :meth:`~scrapy.core.engine.ExecutionEngine.start_async` now raises+ :exc:`RuntimeError` if called before+ :meth:`~scrapy.core.engine.ExecutionEngine.open_spider_async` has+ finished, instead of sending the :signal:`engine_started` signal+ anyway.++ - If the spider is closed before the engine is started, for example by+ calling :meth:`~scrapy.core.engine.ExecutionEngine.close_spider_async`+ from a :signal:`spider_opened` handler, the :signal:`engine_started` and+ :signal:`engine_stopped` signals are not sent.++ - :meth:`Crawler.stop_async() <scrapy.crawler.Crawler.stop_async>`, when+ called while the spider is being opened, now closes the spider as soon+ as it is open, instead of being ignored.++ (TBD)++- Setting the :attr:`ExecutionEngine.running+ <scrapy.core.engine.ExecutionEngine.running>` attribute no longer has any+ effect.+ (:gh:`8181`)+.. _release-2.19.0:Scrapy 2.19.0 (2026-09-10)diff --git a/docs/topics/api.rst b/docs/topics/api.rstindex 4e3ea5a61..acc09511d 100644--- a/docs/topics/api.rst+++ b/docs/topics/api.rst@@ -215,4 +215,7 @@ Engine API==========.. autoclass:: scrapy.core.engine.ExecutionEngine()- :members: needs_backout, running, scheduler+ :members: needs_backout, running, scheduler, state++.. autoclass:: scrapy.core.engine.EngineState+ :members:diff --git a/docs/topics/signals.rst b/docs/topics/signals.rstindex 9310da7d7..66fd3320e 100644--- a/docs/topics/signals.rst+++ b/docs/topics/signals.rst@@ -140,7 +140,8 @@ engine_stopped.. function:: engine_stopped()Sent when the Scrapy engine is stopped (for example, when a crawling- process has finished).+ process has finished). It is sent only after all :signal:`engine_started`+ handlers have completed.This signal supports :ref:`asynchronous handlers <signal-deferred>`.diff --git a/scrapy/commands/shell.py b/scrapy/commands/shell.pyindex 532edd4f8..f64f557b5 100644--- a/scrapy/commands/shell.py+++ b/scrapy/commands/shell.py@@ -11,6 +11,7 @@ from threading import Threadfrom typing import TYPE_CHECKING, Any, ClassVarfrom scrapy.commands import ScrapyCommand+from scrapy.core.engine import ExecutionEnginefrom scrapy.crawler import AsyncCrawlerProcess, Crawlerfrom scrapy.http import Requestfrom scrapy.shell import Shell@@ -96,7 +97,7 @@ class Command(ScrapyCommand):def _init_with_reactor(self, crawler: Crawler) -> None:# Create the engine in the main thread- crawler.engine = crawler._create_engine()+ crawler.engine = ExecutionEngine(crawler)self._start_crawler_thread()def _init_without_reactor(self, crawler: Crawler) -> None:@@ -105,7 +106,7 @@ class Command(ScrapyCommand):self._start_crawler_thread()async def _init_engine() -> None:- crawler.engine = crawler._create_engine()+ crawler.engine = ExecutionEngine(crawler)future = asyncio.run_coroutine_threadsafe(_init_engine(), loop)future.result()diff --git a/scrapy/core/engine.py b/scrapy/core/engine.pyindex b86fe233d..f9e9efd9a 100644--- a/scrapy/core/engine.py+++ b/scrapy/core/engine.py@@ -64,40 +64,61 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-class _EngineState(Enum):- """The lifecycle state of ExecutionEngine.+class EngineState(Enum):+ """The lifecycle state of :class:`ExecutionEngine`.- The engine goes through these states in order, possibly skipping some."""+ .. versionadded:: VERSION++ The engine goes through these states in order, possibly skipping some.+ """- # The engine has been created but no spider has been opened yet.CREATED = "created"- # open_spider_async() is running.+ """The engine has been created but no spider has been opened yet."""+SPIDER_OPENING = "spider_opening"- # The spider is open but start_async() has not been called yet.+ """The spider is being opened. The :signal:`spider_opened` signal may be in+ flight."""+SPIDER_OPEN = "spider_open"- # start_async() is running, engine_started may be in flight.+ """The spider is open but the engine has not been started yet. Requests can+ be made via :meth:`~scrapy.core.engine.ExecutionEngine.download_async`."""+STARTING = "starting"- # The engine is running.+ """The engine is being started. The :signal:`engine_started` signal may be+ in flight."""+RUNNING = "running"- # stop_async() is running, engine_stopped has not been sent yet.+ """The engine is running. Start requests and requests from callbacks are+ processed."""++ SPIDER_CLOSING = "spider_closing"+ """The spider is being closed. The :signal:`spider_closed` signal may be in+ flight. The engine is no longer considered running. Scheduled requests are+ no longer sent."""+STOPPING = "stopping"- # The engine has been stopped and cannot be reused.+ """The spider has been closed. The :signal:`engine_started` or+ :signal:`engine_stopped` signal may be in flight."""+STOPPED = "stopped"+ """The engine has been stopped and cannot be reused."""-_STATE_TRANSITIONS: dict[_EngineState, frozenset[_EngineState]] = {- # Shortcut to STOPPED: close_async() without a spider- _EngineState.CREATED: frozenset(- {_EngineState.SPIDER_OPENING, _EngineState.STOPPED}+_STATE_TRANSITIONS: dict[EngineState, frozenset[EngineState]] = {+ # Shortcut to STOPPED: stopping without a spider+ EngineState.CREATED: frozenset({EngineState.SPIDER_OPENING, EngineState.STOPPED}),+ EngineState.SPIDER_OPENING: frozenset({EngineState.SPIDER_OPEN}),+ # Shortcut to SPIDER_CLOSING: stopping without starting+ EngineState.SPIDER_OPEN: frozenset(+ {EngineState.STARTING, EngineState.SPIDER_CLOSING}),- _EngineState.SPIDER_OPENING: frozenset({_EngineState.SPIDER_OPEN}),- # Shortcut to STOPPED: close_async() before start_async()- _EngineState.SPIDER_OPEN: frozenset({_EngineState.STARTING, _EngineState.STOPPED}),- # Shortcut to STOPPING: stop_async() from an engine_started handler- _EngineState.STARTING: frozenset({_EngineState.RUNNING, _EngineState.STOPPING}),- _EngineState.RUNNING: frozenset({_EngineState.STOPPING}),- _EngineState.STOPPING: frozenset({_EngineState.STOPPED}),- _EngineState.STOPPED: frozenset(),+ # Shortcut to SPIDER_CLOSING: stopping from an engine_started handler+ EngineState.STARTING: frozenset({EngineState.RUNNING, EngineState.SPIDER_CLOSING}),+ EngineState.RUNNING: frozenset({EngineState.SPIDER_CLOSING}),+ # Shortcut to STOPPED: stopping without starting+ EngineState.SPIDER_CLOSING: frozenset({EngineState.STOPPING, EngineState.STOPPED}),+ EngineState.STOPPING: frozenset({EngineState.STOPPED}),+ EngineState.STOPPED: frozenset(),}@@ -143,9 +164,9 @@ class ExecutionEngine:def __init__(self,crawler: Crawler,- spider_closed_callback: Callable[- [Spider], Coroutine[Any, Any, None] | Deferred[None] | None- ],+ spider_closed_callback: (+ Callable[[Spider], Coroutine[Any, Any, None] | Deferred[None] | None] | None+ ) = None,) -> None:self.crawler: Crawler = crawlerself.settings: Settings = crawler.settings@@ -153,19 +174,31 @@ class ExecutionEngine:self.logformatter: LogFormatter = crawler.logformatterself._slot: _Slot | None = Noneself.spider: Spider | None = None- self._state: _EngineState = _EngineState.CREATED+ self._state: EngineState = EngineState.CREATED+ # The reason and error flag of a close requested while the spider is+ # opening.+ self._pending_close: tuple[str, bool] | None = Noneself._stop_mode: _StopMode = "graceful"self._downloader_fast_stopped: bool = Falseself.paused: bool = False- self._spider_closed_callback: Callable[- [Spider], Coroutine[Any, Any, None] | Deferred[None] | None- ] = spider_closed_callback+ if spider_closed_callback is not None:+ warnings.warn(+ "The spider_closed_callback argument of ExecutionEngine is"+ " deprecated: closing the spider now stops the engine, and"+ " Crawler.crawl_async() completes when that happens.",+ ScrapyDeprecationWarning,+ stacklevel=2,+ )+ self._spider_closed_callback: (+ Callable[[Spider], Coroutine[Any, Any, None] | Deferred[None] | None] | None+ ) = spider_closed_callbackself.start_time: float | None = Noneself._start: AsyncIterator[Any] | None = None# Whether Spider.start() raised, i.e. some start items or requests may# never have reached the engine.self._start_error: bool = Falseself._closewait: Deferred[None] | None = None+ self._sending_engine_started: bool = Falseself._start_request_processing_awaitable: (asyncio.Future[None] | Deferred[None] | None) = None@@ -209,15 +242,22 @@ class ExecutionEngine:"""return self._slot.scheduler if self._slot is not None else None+ @property+ def state(self) -> EngineState:+ """The current lifecycle state of the engine.++ .. versionadded:: VERSION+ """+ return self._state+@propertydef running(self) -> bool:- """Whether the engine is running, i.e. :meth:`start_async` has started- processing requests and :meth:`stop_async` has not been called yet.+ """Whether the engine is in the :attr:`EngineState.RUNNING` state... versionchanged:: VERSIONBecame a read-only property."""- return self._state is _EngineState.RUNNING+ return self._state is EngineState.RUNNING@running.setterdef running(self, value: bool) -> None:@@ -227,7 +267,7 @@ class ExecutionEngine:stacklevel=2,)- def _transition_to(self, state: _EngineState) -> None:+ def _transition_to(self, state: EngineState) -> None:"""Set the state, validating the transition.If the transition is invalid, a warning is logged and the transition@@ -254,32 +294,41 @@ class ExecutionEngine:"""Start the execution engine... versionadded:: 2.14++ Completes when the engine is stopped.++ Raises :exc:`RuntimeError` if the spider is not open, or if the engine+ has already been started or stopped.++ .. versionchanged:: VERSION+ Now raises :exc:`RuntimeError` instead of returning if the spider+ is not open."""- if self._state not in (- _EngineState.CREATED,- _EngineState.SPIDER_OPENING,- _EngineState.SPIDER_OPEN,- ):- raise RuntimeError("Engine already running")+ if self._state is not EngineState.SPIDER_OPEN:+ raise RuntimeError(+ f"Cannot start the engine in the {self._state.name} state"+ )self.start_time = time()- self._transition_to(_EngineState.STARTING)- await self.signals.send_catch_log_async(signal=signals.engine_started)- if self._state in (_EngineState.STOPPING, _EngineState.STOPPED):- # An engine_started handler stopped the engine.- # Band-aid until the next stage of https://github.com/scrapy/scrapy/issues/6916- return- if self.spider is None:- # require an opened spider- return- self._transition_to(_EngineState.RUNNING)+ self._transition_to(EngineState.STARTING)+ # Fired by _finish_stop() once the engine is stopped.self._closewait = Deferred()- coro = self._start_request_processing()- if is_asyncio_available():- # not wrapping in a Deferred here to avoid https://github.com/twisted/twisted/issues/12470- # (can happen when this is cancelled, e.g. in test_close_during_start_iteration())- self._start_request_processing_awaitable = asyncio.ensure_future(coro)- else:- self._start_request_processing_awaitable = Deferred.fromCoroutine(coro)+ self._sending_engine_started = True+ await self.signals.send_catch_log_async(signal=signals.engine_started)+ self._sending_engine_started = False+ # Make sure that the engine_started handler didn't initiate stopping.+ if self.state is EngineState.STARTING:+ self._transition_to(EngineState.RUNNING)+ coro = self._start_request_processing()+ if is_asyncio_available():+ # not wrapping in a Deferred here to avoid https://github.com/twisted/twisted/issues/12470+ # (can happen when this is cancelled, e.g. in test_close_during_start_iteration())+ self._start_request_processing_awaitable = asyncio.ensure_future(coro)+ else:+ self._start_request_processing_awaitable = Deferred.fromCoroutine(coro)+ elif self.state is EngineState.STOPPING:+ # The spider was closed while engine_started handlers were+ # running, and close_spider_async() left the rest to this method.+ await self._finish_stop()with contextlib.suppress(asyncio.exceptions.CancelledError):await maybe_deferred_to_future(self._closewait)@@ -294,53 +343,18 @@ class ExecutionEngine:return deferred_from_coro(self.stop_async(mode=mode))async def stop_async(self, *, mode: _StopMode = "graceful") -> None:- """Gracefully stop the execution engine.+ """Stop the execution engine by closing the spider with the+ ``shutdown`` reason... versionadded:: 2.14- """+ .. versionchanged:: VERSION+ This is now a shortcut for :meth:`close_spider_async`, see its docs+ for the behavior in different engine states, including when it+ completes.+ """mode = _normalize_stop_mode(mode, allow_force=False)-- if self._state in (- _EngineState.CREATED,- _EngineState.SPIDER_OPENING,- _EngineState.SPIDER_OPEN,- ):- raise RuntimeError("Engine not running")-- self._stop_mode = _max_stop_mode(self._stop_mode, mode)-- if self._state in (_EngineState.STOPPING, _EngineState.STOPPED):- if self.spider is not None and self._stop_mode == "fast":- await self.close_spider_async(reason="shutdown", mode="fast")- if self._closewait:- await maybe_deferred_to_future(self._closewait)- return-- self._transition_to(_EngineState.STOPPING)- if self._start_request_processing_awaitable is not None:- if (- not is_asyncio_available()- or self._start_request_processing_awaitable- is not asyncio.current_task()- ):- # If using the asyncio loop and stop_async() was called from- # start() itself, we can't cancel it, and _start_request_processing()- # will exit via the self.running check.- self._start_request_processing_awaitable.cancel()- self._start_request_processing_awaitable = None- if self.spider is not None:- await self.close_spider_async(reason="shutdown", mode=self._stop_mode)- else:- # Normally it's close_spider_async() that does this.- self.downloader.close()- await self.signals.send_catch_log_async(signal=signals.engine_stopped)- # Firing _closewait can resume start_async(), and with it the code- # awaiting start_async(), before this method continues, so the engine- # must already be STOPPED when that code checks the state.- self._transition_to(_EngineState.STOPPED)- if self._closewait:- self._closewait.callback(None)+ await self.close_spider_async(reason="shutdown", mode=mode)def close(self) -> Deferred[None]: # pragma: no coverwarnings.warn(@@ -353,20 +367,17 @@ class ExecutionEngine:async def close_async(self, *, reason: str = "shutdown", error: bool = False) -> None:+ """Stop the execution engine.++ This is safe to call in any engine state. If a spider has been opened,+ this is an alias for :meth:`close_spider_async`."""- Gracefully close the execution engine.- If it has already been started, stop it. In all cases, close the spider and the downloader.- """- if self.running:- await self.stop_async() # will also close spider and downloader- return- if self.spider is not None:- # will also close downloader- await self.close_spider_async(reason=reason, error=error)- else:+ if self._state is EngineState.CREATED:+ # Only the downloader needs closing.self.downloader.close()- if self._state not in (_EngineState.STOPPING, _EngineState.STOPPED):- self._transition_to(_EngineState.STOPPED)+ self._transition_to(EngineState.STOPPED)+ return+ await self.close_spider_async(reason=reason, error=error)def pause(self) -> None:self.paused = True@@ -587,9 +598,9 @@ class ExecutionEngine:async def download_async(self, request: Request) -> Response:"""Return a coroutine which fires with a Response as result.- Only downloader middlewares are applied.-.. versionadded:: 2.14++ Only downloader middlewares are applied."""if self.spider is None:raise RuntimeError(f"No open spider to crawl: {request}")@@ -652,13 +663,22 @@ class ExecutionEngine:return deferred_from_coro(self.open_spider_async(close_if_idle=close_if_idle))async def open_spider_async(self, *, close_if_idle: bool = True) -> None:+ """Open the spider.++ Raises :exc:`RuntimeError` if a spider has already been opened.+ """assert self.crawler.spider- if self._slot is not None:+ if self._state is EngineState.STOPPED:+ raise RuntimeError(+ f"Cannot open spider {self.crawler.spider.name!r}:"+ f" the engine has already been stopped"+ )+ if self._state is not EngineState.CREATED:raise RuntimeError(f"No free spider slot when opening {self.crawler.spider.name!r}")scheduler = build_from_crawler(self.scheduler_cls, self.crawler)- self._transition_to(_EngineState.SPIDER_OPENING)+ self._transition_to(EngineState.SPIDER_OPENING)logger.info("Spider opened", extra={"spider": self.crawler.spider})self.spider = self.crawler.spidernextcall = CallLaterOnce(self._start_scheduled_requests)@@ -700,7 +720,16 @@ class ExecutionEngine:finally:# Partially open counts as open because we still want to close the# components that were opened (close_spider_async() will do that).- self._transition_to(_EngineState.SPIDER_OPEN)+ self._transition_to(EngineState.SPIDER_OPEN)+ await self._close_spider_if_pending()++ async def _close_spider_if_pending(self) -> None:+ """Perform a close requested while the spider was opening."""+ if self._pending_close is None:+ return+ reason, error = self._pending_close+ self._pending_close = None+ await self.close_spider_async(reason=reason, error=error)def _spider_idle(self) -> None:"""@@ -779,26 +808,76 @@ class ExecutionEngine:mode: _StopMode = "graceful",error: bool = False,) -> None:- """Close (cancel) spider and clear all its outstanding requests.+ """Close (cancel) spider and clear all its outstanding requests, and+ stop the engine... versionadded:: 2.14- """- mode = _normalize_stop_mode(mode, allow_force=False)- self._stop_mode = _max_stop_mode(self._stop_mode, mode)- if self.spider is None:- raise RuntimeError("Spider not opened")+ *reason* is the spider finish reason (see the :stat:`finish_reason`+ stat). *error* is a flag that specifies whether the crawl should be+ considered failed (see the :stat:`finish_reason_error` stat). If+ *mode* is ``"graceful"``, this method will wait until the requests+ that are already in the downloader are downloaded and processed; if+ it's ``"fast"`` they will be dropped.- if self._slot is None:- raise RuntimeError("Engine slot not assigned")+ If the spider was not opened before, this method raises+ :exc:`RuntimeError`.++ If the spider is still opening, this method completes immediately, and+ the spider will start closing after it finishes opening, with the+ *reason* and *error* of the first such call.- if self._slot.closing is not None:+ If the spider is closing or has already been closed, this method+ completes immediately, ignoring *reason* and *error*. If+ ``mode="fast"`` was passed, it will also drop the requests left in the+ downloader.++ .. versionchanged:: VERSION+ Previously, calling it while the spider was closing waited for the+ in-flight requests to finish, and calling it after the spider had+ been closed raised :exc:`RuntimeError`.++ Otherwise, this method completes after the spider has been closed and+ the engine has stopped. If :signal:`engine_started` handlers are still+ running at that point, the engine stops once they finish, and this+ method completes without waiting for that.+ """+ mode = _normalize_stop_mode(mode, allow_force=False)+ if self._state is EngineState.CREATED:+ raise RuntimeError("Spider not opened")+ self._stop_mode = _max_stop_mode(self._stop_mode, mode)+ if self._state in (EngineState.STOPPING, EngineState.STOPPED):+ return+ if self._state is EngineState.SPIDER_CLOSING:+ # Waiting until it closes may deadlock (if a handler called in this+ # method calls this method again), but a fast stop can still drop+ # the in-flight downloads that it may be waiting for.if self._stop_mode == "fast":await self._fast_stop_downloader()- await maybe_deferred_to_future(self._slot.closing)+ return+ if self._state is EngineState.SPIDER_OPENING:+ # Waiting until it opens similarly may deadlock.+ # _close_spider_if_pending() will close it at the end of+ # open_spider_async().+ if self._pending_close is None:+ self._pending_close = (reason, error)return+ assert self._slot is not None+ assert self.spider is not Nonespider = self.spider+ self._transition_to(EngineState.SPIDER_CLOSING)+ if self._start_request_processing_awaitable is not None:+ if (+ not is_asyncio_available()+ or self._start_request_processing_awaitable+ is not asyncio.current_task()+ ):+ # If using the asyncio loop and this was called from+ # _start_request_processing() itself, we can't cancel it, and+ # it will exit via the self.running check.+ self._start_request_processing_awaitable.cancel()+ self._start_request_processing_awaitable = Nonelogger.info("Closing spider (%(reason)s)", {"reason": reason}, extra={"spider": spider}@@ -865,7 +944,32 @@ class ExecutionEngine:self._slot = Noneself.spider = None- try:- await ensure_awaitable(self._spider_closed_callback(spider))- except Exception:- logger.error("Error running spider_closed_callback")+ if self._spider_closed_callback is not None:+ try:+ await ensure_awaitable(self._spider_closed_callback(spider))+ except Exception:+ logger.error("Error running spider_closed_callback")++ # Stop the engine+ if self._closewait is None:+ # The engine was never started, so there is nothing to stop.+ self._transition_to(EngineState.STOPPED)+ return+ self._transition_to(EngineState.STOPPING)+ if self._sending_engine_started:+ # engine_stopped handlers may undo what engine_started handlers do,+ # so start_async() sends engine_stopped once the latter finish.+ # Waiting for them here would deadlock if one of them awaits this+ # method.+ return+ await self._finish_stop()++ async def _finish_stop(self) -> None:+ """Send :signal:`engine_stopped` and mark the engine as stopped."""+ assert self._closewait is not None+ await self.signals.send_catch_log_async(signal=signals.engine_stopped)+ # Firing _closewait can resume start_async(), and with it the code+ # awaiting start_async(), before this method continues, so the+ # engine must already be STOPPED when that code checks the state.+ self._transition_to(EngineState.STOPPED)+ self._closewait.callback(None)diff --git a/scrapy/crawler.py b/scrapy/crawler.pyindex 4b83e47c1..07764eea7 100644--- a/scrapy/crawler.py+++ b/scrapy/crawler.py@@ -14,7 +14,7 @@ from twisted.internet.defer import Deferred, DeferredList, inlineCallbacksfrom scrapy import Spiderfrom scrapy.addons import AddonManager-from scrapy.core.engine import ExecutionEngine+from scrapy.core.engine import EngineState, ExecutionEnginefrom scrapy.exceptions import CloseSpider, ScrapyDeprecationWarningfrom scrapy.extension import ExtensionManagerfrom scrapy.settings import SETTINGS_PRIORITIES, Settings, overridden_settings@@ -299,7 +299,7 @@ class Crawler:self.spider = self._create_spider(*args, **kwargs)self._apply_settings()self._update_root_log_handler()- self.engine = self._create_engine()+ self.engine = ExecutionEngine(self)try:yield deferred_from_coro(self.engine.open_spider_async())except CloseSpider as exc:@@ -307,12 +307,16 @@ class Crawler:self.engine.close_async(reason=exc.reason, error=exc.error))else:- yield deferred_from_coro(self.engine.start_async())+ # The spider may have been closed already, e.g. by an+ # extension, in which case the engine is already stopped.+ if self.engine.state is EngineState.SPIDER_OPEN:+ yield deferred_from_coro(self.engine.start_async())except Exception:- self.crawling = Falseif self._engine is not None:yield deferred_from_coro(self._engine.close_async())raise+ finally:+ self.crawling = Falseasync def crawl_async(self, *args: Any, **kwargs: Any) -> None:"""Start the crawler by instantiating its spider class with the given@@ -335,28 +339,28 @@ class Crawler:self.spider = self._create_spider(*args, **kwargs)self._apply_settings()self._update_root_log_handler()- self.engine = self._create_engine()+ self.engine = ExecutionEngine(self)try:await self.engine.open_spider_async()except CloseSpider as exc:await self.engine.close_async(reason=exc.reason, error=exc.error)else:- await self.engine.start_async()+ # The spider may have been closed already, e.g. by an+ # extension, in which case the engine is already stopped.+ if self.engine.state is EngineState.SPIDER_OPEN:+ await self.engine.start_async()except Exception:- self.crawling = Falseif self._engine is not None:await self._engine.close_async()raise+ finally:+ self.crawling = Falsedef _create_spider(self, *args: Any, **kwargs: Any) -> Spider:return self.spidercls.from_crawler(self, *args, **kwargs)- def _create_engine(self) -> ExecutionEngine:- return ExecutionEngine(self, lambda _: self.stop_async())-def stop(self, *, mode: _StopMode = "graceful") -> Deferred[None]:- """Start a graceful stop of the crawler and return a deferred that is- fired when the crawler is stopped."""+ """Stop the crawler."""warnings.warn("Crawler.stop() is deprecated, use stop_async() instead",ScrapyDeprecationWarning,@@ -365,9 +369,18 @@ class Crawler:return deferred_from_coro(self.stop_async(mode=mode))async def stop_async(self, *, mode: _StopMode = "graceful") -> None:- """Start a graceful stop of the crawler and complete when the crawler is stopped.+ """Stop the crawler... versionadded:: 2.14++ .. versionchanged:: VERSION+ Calling it while the spider is being opened now closes the spider+ as soon as it is open.++ Completes when the crawl has finished, except when the spider is still+ being opened or the crawler is already stopping, in which case it+ completes immediately, and when :signal:`engine_started` handlers are+ still running, in which case it completes once the spider is closed."""mode = _normalize_stop_mode(mode)was_crawling = self.crawling@@ -385,19 +398,13 @@ class Crawler:)mode = "fast"- if self._engine is None:+ if self._engine is None or self._engine.state is EngineState.CREATED:+ # Nothing has been opened yet, so there is nothing to stop.return- # During shutdown callbacks, graceful stop may be re-entered after- # the engine has already switched to non-running state.- if mode == "graceful" and not self._engine.running:- return-- try:- await self._engine.stop_async(mode=mode)- except RuntimeError as exc:- if str(exc) != "Engine not running":- raise+ # A no-op if the spider is already closing or closed, except that a+ # fast stop still drops the in-flight downloads.+ await self._engine.stop_async(mode=mode)@staticmethoddef _get_component(@@ -624,7 +631,9 @@ class CrawlerRunner(CrawlerRunnerBase):"""Stops simultaneously all the crawling jobs taking place.- Returns a deferred that is fired when they all have ended.+ Returns a deferred that is fired when all their+ :meth:`Crawler.stop_async() <scrapy.crawler.Crawler.stop_async>` calls+ have completed."""mode = _normalize_stop_mode(mode)return DeferredList(@@ -751,7 +760,8 @@ class AsyncCrawlerRunner(CrawlerRunnerBase):"""Stops simultaneously all the crawling jobs taking place.- Completes when they all have ended.+ Completes when all their :meth:`Crawler.stop_async()+ <scrapy.crawler.Crawler.stop_async>` calls have completed."""mode = _normalize_stop_mode(mode)if self.crawlers:@@ -912,10 +922,19 @@ class CrawlerProcessBase(CrawlerRunnerBase):def _stop_dfd(self, *, mode: _StopMode = "graceful") -> Deferred[Any]:raise NotImplementedError+ @abstractmethod+ def _join_dfd(self) -> Deferred[Any]:+ raise NotImplementedError+@inlineCallbacksdef _graceful_stop_reactor(self) -> Generator[Deferred[Any], Any, None]:try:yield self._stop_dfd(mode="graceful")+ # Crawler.stop_async() returns as soon as the stop is under way+ # (a spider close already in progress finishes it), so wait for+ # the crawls to actually end before stopping the reactor. The next+ # signal stops it regardless.+ yield self._join_dfd()finally:self._stop_reactor()@@ -923,6 +942,7 @@ class CrawlerProcessBase(CrawlerRunnerBase):def _fast_stop_reactor(self) -> Generator[Deferred[Any], Any, None]:try:yield self._stop_dfd(mode="fast")+ yield self._join_dfd() # see _graceful_stop_reactor()finally:self._stop_reactor()@@ -982,6 +1002,9 @@ class CrawlerProcess(CrawlerProcessBase, CrawlerRunner):def _stop_dfd(self, *, mode: _StopMode = "graceful") -> Deferred[Any]:return self.stop(mode=mode)+ def _join_dfd(self) -> Deferred[Any]:+ return self.join()+def start(self, stop_after_crawl: bool = True, install_signal_handlers: bool = True) -> None:@@ -1091,6 +1114,9 @@ class AsyncCrawlerProcess(CrawlerProcessBase, AsyncCrawlerRunner):def _stop_dfd(self, *, mode: _StopMode = "graceful") -> Deferred[Any]:return deferred_from_coro(self.stop(mode=mode))+ def _join_dfd(self) -> Deferred[Any]:+ return deferred_from_coro(self.join())+def start(self, stop_after_crawl: bool = True, install_signal_handlers: bool = True) -> None:diff --git a/scrapy/extensions/remote_control.py b/scrapy/extensions/remote_control.pyindex 22fe82230..cc06d5815 100644--- a/scrapy/extensions/remote_control.py+++ b/scrapy/extensions/remote_control.py@@ -130,6 +130,8 @@ class RemoteControl:self._auth_token: str | None = Noneself._runner: web.AppRunner | None = Noneself._job_file_path: Path | None = None+ # Makes stop() wait until start() finishes.+ self._lock = asyncio.Lock()crawler.signals.connect(self.start, signal=signals.engine_started)crawler.signals.connect(self.stop, signal=signals.engine_stopped)@@ -147,6 +149,10 @@ class RemoteControl:async def start(self) -> None:"""Start the HTTP server."""+ async with self._lock:+ await self._start()++ async def _start(self) -> None:try:self._auth_token = secrets.token_urlsafe(32)app = web.Application()@@ -185,10 +191,14 @@ class RemoteControl:"Remote control HTTP server failed to start",extra={"crawler": self._crawler},)- await self.stop()+ await self._stop()async def stop(self) -> None:"""Stop the HTTP server and remove the job file."""+ async with self._lock:+ await self._stop()++ async def _stop(self) -> None:if self._job_file_path is not None:# we remove the job file before stopping the HTTP serverwith contextlib.suppress(OSError):diff --git a/tests/test_crawler.py b/tests/test_crawler.pyindex 8f56f8921..dfa7792c0 100644--- a/tests/test_crawler.py+++ b/tests/test_crawler.py@@ -13,6 +13,7 @@ import pytestimport scrapyfrom scrapy import Spider+from scrapy.core.engine import EngineStatefrom scrapy.crawler import AsyncCrawlerProcess, Crawler, CrawlerProcessfrom scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.extensions.throttle import AutoThrottle@@ -906,12 +907,12 @@ async def test_crawler_stop_async_invalid_mode() -> None:@coroutine_test-async def test_crawler_graceful_stop_non_running_engine_is_noop() -> None:+async def test_crawler_graceful_stop_created_engine_is_noop() -> None:crawler = get_crawler(DefaultSpider)crawler.crawling = Trueclass DummyEngine:- running = False+ state = EngineState.CREATEDcalled = Falseasync def stop_async(self, *, mode: str = "graceful") -> None:@@ -932,6 +933,7 @@ async def test_crawler_force_stop_falls_back_to_fast(crawler = get_crawler(DefaultSpider)class DummyEngine:+ state = EngineState.RUNNINGcalled_mode: str | None = Noneasync def stop_async(self, *, mode: str = "graceful") -> None:@@ -971,44 +973,6 @@ async def test_crawler_stop_async_without_engine_is_noop() -> None:assert crawler.crawling is False-@coroutine_test-async def test_crawler_stop_async_ignores_engine_not_running_runtime_error() -> None:- crawler = get_crawler(DefaultSpider)- crawler.crawling = True-- class DummyEngine:- running = True- called = False-- async def stop_async(self, *, mode: str = "graceful") -> None:- self.called = True- raise RuntimeError("Engine not running")-- dummy_engine = DummyEngine()- crawler.engine = dummy_engine # type: ignore[assignment]-- await crawler.stop_async(mode="graceful")-- assert dummy_engine.called is True---@coroutine_test-async def test_crawler_stop_async_reraises_other_runtime_errors() -> None:- crawler = get_crawler(DefaultSpider)- crawler.crawling = True-- class DummyEngine:- running = True-- async def stop_async(self, *, mode: str = "graceful") -> None:- raise RuntimeError("different runtime error")-- crawler.engine = DummyEngine() # type: ignore[assignment]-- with pytest.raises(RuntimeError, match="different runtime error"):- await crawler.stop_async(mode="graceful")--@pytest.mark.requires_reactor@coroutine_testasync def test_crawler_process_force_stop_via_public_crawler_api() -> None:diff --git a/tests/test_downloadermiddleware.py b/tests/test_downloadermiddleware.pyindex 163aa70d4..5aebd3160 100644--- a/tests/test_downloadermiddleware.py+++ b/tests/test_downloadermiddleware.py@@ -10,6 +10,7 @@ import pytestfrom twisted.internet.defer import Deferred, succeedfrom scrapy.core.downloader.middleware import DownloaderMiddlewareManager+from scrapy.core.engine import ExecutionEnginefrom scrapy.exceptions import (CloseSpider,DecompressionError,@@ -67,7 +68,7 @@ class TestManagerBase:crawler = get_crawler(Spider, self.settings_dict)crawler.spider = crawler._create_spider("foo")mwman = build_from_crawler(DownloaderMiddlewareManager, crawler)- crawler.engine = crawler._create_engine()+ crawler.engine = ExecutionEngine(crawler)await crawler.engine.open_spider_async()try:yield mwmandiff --git a/tests/test_engine.py b/tests/test_engine.pyindex fc37b3a3b..29b301b7d 100644--- a/tests/test_engine.py+++ b/tests/test_engine.py@@ -8,12 +8,11 @@ from typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, Mock, patchimport pytest-from twisted.internet import deferfrom twisted.python.failure import Failurefrom scrapy import signalsfrom scrapy.core.downloader import Downloader-from scrapy.core.engine import ExecutionEngine, _EngineState, _Slot+from scrapy.core.engine import EngineState, ExecutionEngine, _Slotfrom scrapy.core.scheduler import BaseSchedulerfrom scrapy.exceptions import (CloseSpider,@@ -23,7 +22,6 @@ from scrapy.exceptions import ()from scrapy.http import Requestfrom scrapy.spiders import Spider-from scrapy.utils.asyncio import sleepfrom scrapy.utils.defer import (_schedule_coro,deferred_from_coro,@@ -140,7 +138,7 @@ class TestEngine(TestEngineBase):@coroutine_testasync def test_close_downloader(self):- e = ExecutionEngine(get_crawler(MySpider), lambda _: None)+ e = ExecutionEngine(get_crawler(MySpider))await e.close_async()def test_close_without_downloader(self):@@ -152,74 +150,66 @@ class TestEngine(TestEngineBase):raise CustomExceptionwith pytest.raises(CustomException):- ExecutionEngine(- get_crawler(MySpider, {"DOWNLOADER": BadDownloader}), lambda _: None- )+ ExecutionEngine(get_crawler(MySpider, {"DOWNLOADER": BadDownloader}))@inline_callbacks_testdef test_start_already_running_exception(self):crawler = get_crawler(DefaultSpider)crawler.spider = crawler._create_spider()- e = ExecutionEngine(crawler, lambda _: None)+ e = ExecutionEngine(crawler)crawler.engine = eyield deferred_from_coro(e.open_spider_async())_schedule_coro(e.start_async())- with pytest.raises(RuntimeError, match="Engine already running"):+ with pytest.raises(RuntimeError, match=r"in the (STARTING|RUNNING) state"):yield deferred_from_coro(e.start_async())yield deferred_from_coro(e.stop_async())@coroutine_testasync def test_stop_async_force_mode_not_supported(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))with pytest.raises(ValueError, match="force stop mode is not supported"):await engine.stop_async(mode="force")@coroutine_testasync def test_stop_async_not_running_raises(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))- with pytest.raises(RuntimeError, match="Engine not running"):+ with pytest.raises(RuntimeError, match="Spider not opened"):await engine.stop_async()@coroutine_test- async def test_stop_async_reentrant_fast_waits_for_closewait(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)- engine.spider = Mock()- engine._state = _EngineState.STOPPING- engine._closewait = defer.Deferred()+ async def test_stop_async_reentrant_fast_drops_downloads(self) -> None:+ """A fast stop requested while the spider is already closing drops+ the in-flight downloads, and returns without waiting for the close."""+ engine = ExecutionEngine(get_crawler(DefaultSpider))+ engine._state = EngineState.SPIDER_CLOSINGwith patch.object(- engine, "close_spider_async", new_callable=AsyncMock- ) as close:- stop_dfd = deferred_from_coro(engine.stop_async(mode="fast"))- await sleep(0)- close.assert_called_once_with(reason="shutdown", mode="fast")- assert not stop_dfd.called+ engine, "_fast_stop_downloader", new_callable=AsyncMock+ ) as fast_stop:+ await engine.stop_async(mode="fast")- assert engine._closewait- engine._closewait.callback(None)- await maybe_deferred_to_future(stop_dfd)+ fast_stop.assert_awaited_once()+ assert engine._stop_mode == "fast"@coroutine_test- async def test_stop_async_reentrant_graceful_without_spider_or_closewait(- self,- ) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)- engine._state = _EngineState.STOPPING+ async def test_stop_async_reentrant_graceful_is_noop(self) -> None:+ engine = ExecutionEngine(get_crawler(DefaultSpider))+ engine._state = EngineState.SPIDER_CLOSINGwith patch.object(- engine, "close_spider_async", new_callable=AsyncMock- ) as close:+ engine, "_fast_stop_downloader", new_callable=AsyncMock+ ) as fast_stop:await engine.stop_async(mode="graceful")- close.assert_not_called()+ fast_stop.assert_not_called()@coroutine_testasync def test_handle_downloader_output_ignores_fast_cancelled_failures(self,) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))engine.spider = Mock()engine._stop_mode = "fast"@@ -238,10 +228,10 @@ class TestEngine(TestEngineBase):async def test_start_already_running_exception_asyncio(self):crawler = get_crawler(DefaultSpider)crawler.spider = crawler._create_spider()- e = ExecutionEngine(crawler, lambda _: None)+ e = ExecutionEngine(crawler)crawler.engine = eawait e.open_spider_async()- with pytest.raises(RuntimeError, match="Engine already running"):+ with pytest.raises(RuntimeError, match=r"in the (STARTING|RUNNING) state"):await asyncio.gather(e.start_async(), e.start_async())await e.stop_async()@@ -312,7 +302,7 @@ async def test_request_scheduled_signal():raise IgnoreRequestcrawler = get_crawler(MySpider)- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)scheduler = build_from_crawler(TestScheduler, crawler)async def start() -> AsyncIterator[Any]:@@ -385,9 +375,9 @@ class TestMisuse:@coroutine_testasync def test_stop_not_running(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))try:- with pytest.raises(RuntimeError, match="Engine not running"):+ with pytest.raises(RuntimeError, match="Spider not opened"):await engine.stop_async()finally:await engine.close_async()@@ -399,14 +389,11 @@ class TestMisuse:with pytest.raises(TypeError, match="does not fully implement the scheduler interface"):- ExecutionEngine(- get_crawler(DefaultSpider, {"SCHEDULER": NotAScheduler}),- lambda _: None,- )+ ExecutionEngine(get_crawler(DefaultSpider, {"SCHEDULER": NotAScheduler}))@coroutine_testasync def test_spider_is_idle_without_slot(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))try:with pytest.raises(RuntimeError, match="Engine slot not assigned"):engine.spider_is_idle()@@ -415,7 +402,7 @@ class TestMisuse:@coroutine_testasync def test_crawl_without_spider(self) -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))try:with pytest.raises(RuntimeError, match="No open spider to crawl"):engine.crawl(Request("data:,"))@@ -426,7 +413,7 @@ class TestMisuse:async def test_open_spider_twice(self) -> None:crawler = get_crawler(DefaultSpider)crawler.spider = crawler._create_spider()- engine = crawler.engine = ExecutionEngine(crawler, lambda _: None)+ engine = crawler.engine = ExecutionEngine(crawler)await engine.open_spider_async()try:with pytest.raises(RuntimeError, match="No free spider slot"):@@ -464,23 +451,18 @@ async def test_scheduler_creation_error() -> None:@coroutine_test-async def test_stop_without_spider_closes_downloader(- caplog: pytest.LogCaptureFixture,-) -> None:- crawler = get_crawler(DefaultSpider)- engine = crawler.engine = ExecutionEngine(crawler, lambda _: None)- engine.downloader.close = Mock(wraps=engine.downloader.close) # type: ignore[method-assign]- with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):- await engine.start_async()- # Starting without a spider is not part of the engine lifecycle.- assert "Invalid engine state transition: CREATED → STARTING" in caplog.text- await engine.stop_async()- engine.downloader.close.assert_called_once()+async def test_start_without_spider() -> None:+ engine = ExecutionEngine(get_crawler(DefaultSpider))+ try:+ with pytest.raises(RuntimeError, match="in the CREATED state"):+ await engine.start_async()+ finally:+ await engine.close_async()@coroutine_testasync def test_pause_unpause() -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)+ engine = ExecutionEngine(get_crawler(DefaultSpider))try:engine.pause()assert engine.pauseddiff --git a/tests/test_engine_close_spider.py b/tests/test_engine_close_spider.pyindex df572e4e5..42a3b8ad7 100644--- a/tests/test_engine_close_spider.py+++ b/tests/test_engine_close_spider.py@@ -8,6 +8,7 @@ from twisted.internet import deferfrom scrapy import signalsfrom scrapy.core.engine import ExecutionEngine+from scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.statscollectors import MemoryStatsCollectorfrom scrapy.utils.spider import DefaultSpiderfrom scrapy.utils.test import get_crawler@@ -25,23 +26,9 @@ def crawler() -> Crawler:return crawler-@coroutine_test-async def test_no_slot(crawler: Crawler) -> None:- engine = ExecutionEngine(crawler, lambda _: None)- crawler.engine = engine- await engine.open_spider_async()- slot = engine._slot- engine._slot = None- with pytest.raises(RuntimeError, match="Engine slot not assigned"):- await engine.close_spider_async()- # close it correctly- engine._slot = slot- await engine.close_spider_async()--@coroutine_testasync def test_no_spider(crawler: Crawler) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)with pytest.raises(RuntimeError, match="Spider not opened"):await engine.close_spider_async()engine.downloader.close() # cleanup@@ -51,7 +38,7 @@ async def test_no_spider(crawler: Crawler) -> None:async def test_exception_slot(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()assert engine._slot@@ -64,7 +51,7 @@ async def test_exception_slot(async def test_exception_downloader(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()del engine.downloader.slots@@ -76,7 +63,7 @@ async def test_exception_downloader(async def test_exception_scraper(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()engine.scraper.slot = None@@ -88,7 +75,7 @@ async def test_exception_scraper(async def test_exception_scheduler(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()assert engine._slot@@ -101,7 +88,7 @@ async def test_exception_scheduler(async def test_exception_signal(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()signal_manager = engine.signals@@ -120,7 +107,7 @@ async def test_exception_signal(async def test_exception_stats(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()assert isinstance(crawler.stats, MemoryStatsCollector)@@ -133,7 +120,8 @@ async def test_exception_stats(async def test_exception_callback(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: defer.fail(ValueError()))+ with pytest.warns(ScrapyDeprecationWarning, match="spider_closed_callback"):+ engine = ExecutionEngine(crawler, lambda _: defer.fail(ValueError()))crawler.engine = engineawait engine.open_spider_async()await engine.close_spider_async()@@ -147,7 +135,8 @@ async def test_exception_async_callback(async def cb(_):raise ValueError- engine = ExecutionEngine(crawler, cb)+ with pytest.warns(ScrapyDeprecationWarning, match="spider_closed_callback"):+ engine = ExecutionEngine(crawler, cb)crawler.engine = engineawait engine.open_spider_async()await engine.close_spider_async()@@ -158,7 +147,7 @@ async def test_exception_async_callback(async def test_fast_close_stops_downloader_and_records_dropped_requests(crawler: Crawler,) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()@@ -181,7 +170,7 @@ async def test_fast_close_stops_downloader_and_records_dropped_requests(async def test_fast_close_tolerates_downloader_without_stop(crawler: Crawler, caplog: pytest.LogCaptureFixture) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()@@ -203,7 +192,7 @@ async def test_fast_close_tolerates_downloader_without_stop(@coroutine_testasync def test_fast_stop_downloader_is_idempotent(crawler: Crawler) -> None:- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)crawler.engine = engineawait engine.open_spider_async()diff --git a/tests/test_engine_download.py b/tests/test_engine_download.pyindex 09b998f6a..d89adeeee 100644--- a/tests/test_engine_download.py+++ b/tests/test_engine_download.py@@ -17,7 +17,7 @@ from tests.utils.decorators import coroutine_test@pytest.fixturedef engine() -> ExecutionEngine:crawler = get_crawler(DefaultSpider)- engine = ExecutionEngine(crawler, lambda _: None)+ engine = ExecutionEngine(crawler)engine.downloader.close()engine.downloader = Mock()engine._slot = Mock()diff --git a/tests/test_engine_lifecycle.py b/tests/test_engine_lifecycle.pyindex 919105023..d0a614fec 100644--- a/tests/test_engine_lifecycle.py+++ b/tests/test_engine_lifecycle.py@@ -5,10 +5,17 @@ from typing import TYPE_CHECKING, Anyfrom unittest.mock import Mockimport pytest+from twisted.internet.defer import Deferredfrom scrapy import Request, signals-from scrapy.core.engine import ExecutionEngine, _EngineState+from scrapy.core.engine import EngineState, ExecutionEngine+from scrapy.core.scheduler import BaseSchedulerfrom scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils.defer import (+ _schedule_coro,+ deferred_from_coro,+ maybe_deferred_to_future,+)from scrapy.utils.spider import DefaultSpiderfrom scrapy.utils.test import get_crawlerfrom tests.utils.decorators import coroutine_test@@ -17,6 +24,7 @@ if TYPE_CHECKING:from collections.abc import Callablefrom scrapy.crawler import Crawler+ from scrapy.utils._stopmode import _StopModeclass SignalRecorder:@@ -27,7 +35,8 @@ class SignalRecorder:def __init__(self, crawler: Crawler) -> None:self.crawler = crawler- self.calls: list[tuple[str, _EngineState]] = []+ self.calls: list[tuple[str, EngineState]] = []+ self.close_reasons: list[str] = []# Keep strong references to the handlers: signal connections are weak.self._handlers = [self._make_handler(name) for name in self.SIGNALS]for name, handler in zip(self.SIGNALS, self._handlers, strict=True):@@ -36,7 +45,9 @@ class SignalRecorder:def _make_handler(self, name: str) -> Callable[..., None]:def handler(**kwargs: Any) -> None:assert self.crawler.engine is not None- self.calls.append((name, self.crawler.engine._state))+ self.calls.append((name, self.crawler.engine.state))+ if name == "spider_closed":+ self.close_reasons.append(kwargs["reason"])return handler@@ -45,103 +56,669 @@ class SignalRecorder:return [call[0] for call in self.calls]@property- def states(self) -> list[_EngineState]:+ def states(self) -> list[EngineState]:return [call[1] for call in self.calls]-def assert_state(engine: ExecutionEngine, state: _EngineState) -> None:- assert engine._state is state+class BlockingScheduler(BaseScheduler):+ """A scheduler whose close() blocks until unblocked, to keep the engine+ deterministically in the SPIDER_CLOSING state."""++ def __init__(self) -> None:+ self.entered_close: Deferred[None] = Deferred()+ self.unblock_close: Deferred[None] = Deferred()++ def has_pending_requests(self) -> bool:+ return False++ def enqueue_request(self, request: Any) -> bool:+ return True++ def next_request(self) -> Any:+ return None++ def close(self, reason: str) -> Deferred[None]:+ self.entered_close.callback(None)+ return self.unblock_closedef make_engine(crawler: Crawler) -> ExecutionEngine:"""Create the engine of *crawler* as Crawler.crawl_async() (and scrapyshell) would, without opening or starting anything."""crawler.spider = crawler._create_spider()- engine = crawler.engine = crawler._create_engine()+ engine = crawler.engine = ExecutionEngine(crawler)return engine+async def start_engine(engine: ExecutionEngine) -> Deferred[None]:+ """Start *engine* in the background and complete once it has been started.++ Return the Deferred of the ``start_async()`` call, which completes when+ the engine is stopped.+ """+ started: Deferred[None] = Deferred()++ def handler(**kwargs: Any) -> None:+ started.callback(None)++ engine.crawler.signals.connect(handler, signals.engine_started)+ dfd = deferred_from_coro(engine.start_async())+ await maybe_deferred_to_future(started)+ engine.crawler.signals.disconnect(handler, signals.engine_started)+ return dfd+++def assert_state(engine: ExecutionEngine, state: EngineState) -> None:+ assert engine.state is state, engine.state++def assert_no_invalid_transition(caplog: pytest.LogCaptureFixture) -> None:assert not [r for r in caplog.records if "Invalid engine state transition" in r.message]-@coroutine_test-async def test_state_progression(caplog: pytest.LogCaptureFixture) -> None:- crawler = get_crawler(DefaultSpider)- recorder = SignalRecorder(crawler)- with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):+NORMAL_SIGNAL_ORDER = [+ "spider_opened",+ "engine_started",+ "spider_closed",+ "engine_stopped",+]+NEVER_STARTED_SIGNAL_ORDER = ["spider_opened", "spider_closed"]+++class TestNormalLifecycle:+ @coroutine_test+ async def test_state_progression(self, caplog: pytest.LogCaptureFixture) -> None:+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):+ await crawler.crawl_async()+ assert_no_invalid_transition(caplog)+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert not engine.running+ assert not crawler.crawling+ assert recorder.names == NORMAL_SIGNAL_ORDER+ assert recorder.states == [+ EngineState.SPIDER_OPENING,+ EngineState.STARTING,+ EngineState.SPIDER_CLOSING,+ EngineState.STOPPING,+ ]+ assert crawler.stats+ assert crawler.stats.get_value("finish_reason") == "finished"++ @coroutine_test+ async def test_stop_idempotent(self) -> None:+ crawler = get_crawler(DefaultSpider)await crawler.crawl_async()- assert_no_invalid_transition(caplog)- engine = crawler.engine- assert engine is not None- assert_state(engine, _EngineState.STOPPED)- assert not engine.running- assert recorder.names == [- "spider_opened",- "engine_started",- "spider_closed",- "engine_stopped",- ]- assert recorder.states == [- _EngineState.SPIDER_OPENING,- _EngineState.STARTING,- _EngineState.RUNNING,- _EngineState.STOPPING,- ]+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ # None of these raises or hangs on a stopped engine.+ await engine.stop_async()+ await engine.close_async()+ await engine.close_spider_async()+ assert_state(engine, EngineState.STOPPED)-@coroutine_test-async def test_fetch_only_lifecycle(caplog: pytest.LogCaptureFixture) -> None:+class TestFetchOnlyLifecycle:"""The lifecycle used by scrapy shell: the spider is opened, requests aredownloaded, and the engine is never started."""- crawler = get_crawler(DefaultSpider)- recorder = SignalRecorder(crawler)- engine = make_engine(crawler)- assert_state(engine, _EngineState.CREATED)- with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):++ @coroutine_test+ async def test_open_download_close(self, caplog: pytest.LogCaptureFixture) -> None:+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ assert_state(engine, EngineState.CREATED)+ with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):+ await engine.open_spider_async(close_if_idle=False)+ assert_state(engine, EngineState.SPIDER_OPEN)+ assert not engine.running+ response = await engine.download_async(Request("data:,"))+ assert response.status == 200+ # Downloads schedule the slot's next call, which must not start+ # request processing or close the idle spider.+ assert_state(engine, EngineState.SPIDER_OPEN)+ await engine.close_async()+ assert_state(engine, EngineState.STOPPED)+ assert_no_invalid_transition(caplog)+ # The engine was never started, so no engine signals are sent.+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["shutdown"]+++class TestEarlyClose:+ """Closes and stops requested before or while the engine starts."""++ @coroutine_test+ async def test_close_from_engine_started_handler(self) -> None:+ """A close triggered by an engine_started handler must leave the engine+ cleanly stopped instead of half-initialized."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)++ async def stop(**kwargs: Any) -> None:+ await crawler.stop_async()++ crawler.signals.connect(stop, signals.engine_started)+ await crawler.crawl_async()+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER+ assert recorder.states[2] is EngineState.SPIDER_CLOSING+ assert recorder.close_reasons == ["shutdown"]++ @coroutine_test+ async def test_close_during_engine_started_handler(self) -> None:+ """If the spider is closed while an engine_started handler is still+ running, engine_stopped is sent only after that handler finishes."""+ crawler = get_crawler(DefaultSpider)+ events: list[str] = []++ async def engine_started(**kwargs: Any) -> None:+ assert crawler.engine is not None+ await crawler.engine.close_spider_async(reason="early")+ assert_state(crawler.engine, EngineState.STOPPING)+ events.append("engine_started handler finished")++ def engine_stopped(**kwargs: Any) -> None:+ events.append("engine_stopped")++ crawler.signals.connect(engine_started, signals.engine_started)+ crawler.signals.connect(engine_stopped, signals.engine_stopped)+ await crawler.crawl_async()+ assert crawler.engine is not None+ assert_state(crawler.engine, EngineState.STOPPED)+ assert events == ["engine_started handler finished", "engine_stopped"]++ @coroutine_test+ async def test_close_spider_before_start(self) -> None:+ """A spider close that completes before start_async() (e.g. triggered+ by the CloseSpider or MemoryUsage extensions) stops the never-started+ engine right away."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ await engine.close_spider_async(reason="early")+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]+ with pytest.raises(RuntimeError, match="in the STOPPED state"):+ await engine.start_async()++ @pytest.mark.parametrize("use_deferred", [False, True])+ @coroutine_test+ async def test_crawl_with_close_before_start(self, use_deferred: bool) -> None:+ """Crawler.crawl_async() and Crawler.crawl() do not start an engine+ whose spider was closed while opening, and complete without+ hanging."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)++ async def close(**kwargs: Any) -> None:+ assert crawler.engine is not None+ await crawler.engine.close_spider_async(reason="early")++ crawler.signals.connect(close, signals.spider_opened)+ if use_deferred:+ await maybe_deferred_to_future(crawler.crawl())+ else:+ await crawler.crawl_async()+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert not crawler.crawling+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]++ @coroutine_test+ async def test_close_in_progress_at_start(self) -> None:+ """A spider close that is still in progress when start_async() resumes+ after the engine_started signal (e.g. one scheduled by the CloseSpider+ extension while an engine_started handler was running) must not make+ start_async(), and therefore Crawler.crawl_async(), complete before+ the engine is stopped."""+ crawler = get_crawler(+ DefaultSpider, settings_dict={"SCHEDULER": BlockingScheduler}+ )+ recorder = SignalRecorder(crawler)+ close_in_progress: Deferred[None] = Deferred()+ crawl_done_at_engine_stopped: list[bool] = []+ schedulers: list[BlockingScheduler] = []++ async def engine_started(**kwargs: Any) -> None:+ engine = crawler.engine+ assert engine is not None+ scheduler = engine.scheduler+ assert isinstance(scheduler, BlockingScheduler)+ schedulers.append(scheduler)+ _schedule_coro(engine.close_spider_async(reason="early"))+ # Return once the close is under way, blocked in the scheduler.+ await maybe_deferred_to_future(scheduler.entered_close)+ close_in_progress.callback(None)++ def engine_stopped(**kwargs: Any) -> None:+ crawl_done_at_engine_stopped.append(crawl_dfd.called)++ crawler.signals.connect(engine_started, signals.engine_started)+ crawler.signals.connect(engine_stopped, signals.engine_stopped)+ crawl_dfd = deferred_from_coro(crawler.crawl_async())+ await maybe_deferred_to_future(close_in_progress)+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.SPIDER_CLOSING)+ assert not crawl_dfd.called++ schedulers[0].unblock_close.callback(None)+ await maybe_deferred_to_future(crawl_dfd)+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]+ # The crawl completed only after the engine was stopped.+ assert crawl_done_at_engine_stopped == [False]++ @pytest.mark.parametrize("mode", ["graceful", "fast"])+ @coroutine_test+ async def test_crawler_stop_before_start(self, mode: _StopMode) -> None:+ """Crawler.stop_async() before the engine is started (e.g. from a+ spider_opened handler, or on Ctrl-C during a slow spider open) closes+ the spider as soon as it is open, and the crawl neither runs nor+ hangs."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)++ async def stop(**kwargs: Any) -> None:+ await crawler.stop_async(mode=mode)++ crawler.signals.connect(stop, signals.spider_opened)+ await crawler.crawl_async()+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["shutdown"]++ @pytest.mark.parametrize("mode", ["graceful", "fast"])+ @coroutine_test+ async def test_crawler_stop_with_open_spider(self, mode: _StopMode) -> None:+ """Crawler.stop_async() with an open spider and a never-started+ engine closes the spider and stops the engine."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ crawler.crawling = True # as crawl_async() would set+ await engine.open_spider_async()+ await crawler.stop_async(mode=mode)+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["shutdown"]+++class TestCloseDuringOpen:+ @coroutine_test+ async def test_close_spider_during_open(self) -> None:+ """A close requested while the spider is opening is deferred until+ the open finishes, keeping the spider_opened/spider_closed order."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ state_after_close_call: list[EngineState] = []++ async def close(**kwargs: Any) -> None:+ await engine.close_spider_async(reason="early")+ # The first reason wins, as for any other double close.+ await engine.close_spider_async(reason="later")+ state_after_close_call.append(engine.state)++ crawler.signals.connect(close, signals.spider_opened)+ await engine.open_spider_async()+ # The close was deferred, not performed inline in the handler.+ assert state_after_close_call == [EngineState.SPIDER_OPENING]+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]++ @coroutine_test+ async def test_close_spider_during_open_with_error(self) -> None:+ """A close requested while the spider is opening keeps its error+ flag."""+ crawler = get_crawler(DefaultSpider)+ engine = make_engine(crawler)+ errors: list[bool] = []++ async def close(**kwargs: Any) -> None:+ await engine.close_spider_async(reason="early", error=True)++ def closed(error: bool, **kwargs: Any) -> None:+ errors.append(error)++ crawler.signals.connect(close, signals.spider_opened)+ crawler.signals.connect(closed, signals.spider_closed)+ await engine.open_spider_async()+ assert_state(engine, EngineState.STOPPED)+ assert errors == [True]++ @coroutine_test+ async def test_stop_during_open(self) -> None:+ """stop_async() while the spider is opening is performed once the+ spider is open."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)++ async def stop(**kwargs: Any) -> None:+ await engine.stop_async()++ crawler.signals.connect(stop, signals.spider_opened)+ await engine.open_spider_async()+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["shutdown"]++ @coroutine_test+ async def test_close_engine_during_open(self) -> None:+ """close_async() while the spider is opening defers the spider close+ and uses its own reason for it."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)++ async def close(**kwargs: Any) -> None:+ await engine.close_async(reason="early")++ crawler.signals.connect(close, signals.spider_opened)+ await engine.open_spider_async()+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]+++class TestDoubleClose:+ @coroutine_test+ async def test_close_after_close(self) -> None:+ """close_spider_async() after the spider has been closed returns+ instead of raising RuntimeError."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ await engine.close_spider_async(reason="first")+ assert_state(engine, EngineState.STOPPED)+ await engine.close_spider_async(reason="second")+ assert recorder.close_reasons == ["first"]++ @coroutine_test+ async def test_close_while_closing(self) -> None:+ """A concurrent close_spider_async() returns instead of raising or+ starting a second close sequence."""+ crawler = get_crawler(+ DefaultSpider, settings_dict={"SCHEDULER": BlockingScheduler}+ )+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ assert engine._slot is not None+ scheduler = engine._slot.scheduler+ assert isinstance(scheduler, BlockingScheduler)++ first = deferred_from_coro(engine.close_spider_async(reason="first"))+ # Wait until the first close is underway, blocked on scheduler close.+ await maybe_deferred_to_future(scheduler.entered_close)+ assert_state(engine, EngineState.SPIDER_CLOSING)++ await engine.close_spider_async(reason="second")+ assert_state(engine, EngineState.SPIDER_CLOSING) # still the first close++ scheduler.unblock_close.callback(None)+ await maybe_deferred_to_future(first)+ assert_state(engine, EngineState.STOPPED)+ assert recorder.close_reasons == ["first"]++ @coroutine_test+ async def test_stop_while_closing(self) -> None:+ """A stop requested while the spider is closing does not wait for the+ close, and the close finishes the stop, so that engine_stopped is+ still sent after spider_closed."""+ crawler = get_crawler(+ DefaultSpider, settings_dict={"SCHEDULER": BlockingScheduler}+ )+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)await engine.open_spider_async(close_if_idle=False)- assert_state(engine, _EngineState.SPIDER_OPEN)- assert not engine.running- response = await engine.download_async(Request("data:,"))- assert response.status == 200- assert_state(engine, _EngineState.SPIDER_OPEN)+ start_dfd = await start_engine(engine)+ assert engine._slot is not None+ scheduler = engine._slot.scheduler+ assert isinstance(scheduler, BlockingScheduler)++ close_dfd = deferred_from_coro(engine.close_spider_async(reason="first"))+ await maybe_deferred_to_future(scheduler.entered_close)+ assert_state(engine, EngineState.SPIDER_CLOSING)++ await engine.stop_async() # returns without waiting for the close+ assert_state(engine, EngineState.SPIDER_CLOSING)+ assert "engine_stopped" not in recorder.names+ assert not start_dfd.called++ scheduler.unblock_close.callback(None)+ await maybe_deferred_to_future(close_dfd)+ await maybe_deferred_to_future(start_dfd)+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER+ assert recorder.close_reasons == ["first"]++ @coroutine_test+ async def test_stop_from_spider_closed_handler(self) -> None:+ """Stopping the crawler from a spider_closed handler, i.e. from code+ that the close sequence awaits, must not deadlock."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)++ async def stop(**kwargs: Any) -> None:+ await crawler.stop_async()++ crawler.signals.connect(stop, signals.spider_closed)+ await crawler.crawl_async()+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER++ @coroutine_test+ async def test_stop_from_engine_stopped_handler(self) -> None:+ """Stopping the crawler from an engine_stopped handler must not+ deadlock either."""+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)++ async def stop(**kwargs: Any) -> None:+ await crawler.stop_async()++ crawler.signals.connect(stop, signals.engine_stopped)+ await crawler.crawl_async()+ engine = crawler.engine+ assert engine is not None+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER+++class TestInvalidTransitions:+ """Calls that the state does not allow raise instead of transitioning, and+ a transition that the transition table does not allow is logged."""++ @coroutine_test+ async def test_transition_not_in_table_is_logged(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ engine = ExecutionEngine(get_crawler(DefaultSpider))+ with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):+ engine._transition_to(EngineState.RUNNING)+ assert "Invalid engine state transition: CREATED → RUNNING" in caplog.text+ assert_state(engine, EngineState.RUNNING)+ engine.downloader.close()++ @coroutine_test+ async def test_stop_not_opened(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = ExecutionEngine(crawler)+ with pytest.raises(RuntimeError, match="Spider not opened"):+ await engine.stop_async()+ engine.downloader.close()++ @coroutine_test+ async def test_double_open(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ with pytest.raises(RuntimeError, match="No free spider slot"):+ await engine.open_spider_async()+ await engine.close_spider_async()++ @coroutine_test+ async def test_open_after_stop(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = make_engine(crawler)+ await engine.close_async()+ assert_state(engine, EngineState.STOPPED)+ with pytest.raises(RuntimeError, match="engine has already been stopped"):+ await engine.open_spider_async()++ @coroutine_test+ async def test_start_after_stop(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ await engine.close_async()+ with pytest.raises(RuntimeError, match="in the STOPPED state"):+ await engine.start_async()++ @pytest.mark.parametrize(+ ("signal", "message"),+ [+ (+ signals.spider_opened,+ "Cannot start the engine in the SPIDER_OPENING state",+ ),+ (+ signals.spider_closed,+ "Cannot start the engine in the SPIDER_CLOSING state",+ ),+ ],+ )+ @coroutine_test+ async def test_start_while_opening_or_closing(+ self, signal: object, message: str+ ) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = make_engine(crawler)+ errors: list[str] = []++ async def start(**kwargs: Any) -> None:+ try:+ await engine.start_async()+ except RuntimeError as exc:+ errors.append(str(exc))++ crawler.signals.connect(start, signal)+ await engine.open_spider_async()+ await engine.close_spider_async()+ assert errors == [message]++ @coroutine_test+ async def test_close_spider_never_opened(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = ExecutionEngine(crawler)+ with pytest.raises(RuntimeError, match="Spider not opened"):+ await engine.close_spider_async()+ engine.downloader.close()+++class TestCloseAsync:+ """close_async() must work, and clean everything up, in every state."""++ @coroutine_test+ async def test_created(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = ExecutionEngine(crawler)+ engine.downloader.close = Mock(wraps=engine.downloader.close) # type: ignore[method-assign]await engine.close_async()- assert_state(engine, _EngineState.STOPPED)- assert_no_invalid_transition(caplog)- assert recorder.names == ["spider_opened", "spider_closed"]---@coroutine_test-async def test_close_created() -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)- engine.downloader.close = Mock(wraps=engine.downloader.close) # type: ignore[method-assign]- await engine.close_async()- assert_state(engine, _EngineState.STOPPED)- engine.downloader.close.assert_called()---@coroutine_test-async def test_close_stopped(caplog: pytest.LogCaptureFixture) -> None:- crawler = get_crawler(DefaultSpider)- await crawler.crawl_async()- engine = crawler.engine- assert engine is not None- assert_state(engine, _EngineState.STOPPED)- with caplog.at_level(logging.WARNING, logger="scrapy.core.engine"):+ assert_state(engine, EngineState.STOPPED)+ engine.downloader.close.assert_called()++ @coroutine_test+ async def test_open(self) -> None:+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ await engine.close_async()+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NEVER_STARTED_SIGNAL_ORDER+ assert recorder.close_reasons == ["shutdown"]++ @coroutine_test+ async def test_closing(self) -> None:+ """close_async() while the spider is closing leaves the cleanup to+ that close instead of waiting for it."""+ crawler = get_crawler(+ DefaultSpider, settings_dict={"SCHEDULER": BlockingScheduler}+ )+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async()+ assert engine._slot is not None+ scheduler = engine._slot.scheduler+ assert isinstance(scheduler, BlockingScheduler)++ close_dfd = deferred_from_coro(engine.close_spider_async(reason="first"))+ await maybe_deferred_to_future(scheduler.entered_close)await engine.close_async()- assert_state(engine, _EngineState.STOPPED)- assert_no_invalid_transition(caplog)---@coroutine_test-async def test_running_setter_deprecated() -> None:- engine = ExecutionEngine(get_crawler(DefaultSpider), lambda _: None)- with pytest.warns(- ScrapyDeprecationWarning,- match="Setting ExecutionEngine.running is deprecated",- ):- engine.running = True- assert engine.running is False # setting it has no effect- engine.downloader.close()+ assert_state(engine, EngineState.SPIDER_CLOSING)++ scheduler.unblock_close.callback(None)+ await maybe_deferred_to_future(close_dfd)+ assert_state(engine, EngineState.STOPPED)+ assert recorder.close_reasons == ["first"]++ @coroutine_test+ async def test_running(self) -> None:+ crawler = get_crawler(DefaultSpider)+ recorder = SignalRecorder(crawler)+ engine = make_engine(crawler)+ await engine.open_spider_async(close_if_idle=False)+ start_dfd = await start_engine(engine)+ await engine.close_async(reason="early")+ assert_state(engine, EngineState.STOPPED)+ assert recorder.names == NORMAL_SIGNAL_ORDER+ assert recorder.close_reasons == ["early"]+ await maybe_deferred_to_future(start_dfd)+++class TestDeprecated:+ @coroutine_test+ async def test_running_setter(self) -> None:+ crawler = get_crawler(DefaultSpider)+ engine = ExecutionEngine(crawler)+ with pytest.warns(+ ScrapyDeprecationWarning,+ match="Setting ExecutionEngine.running is deprecated",+ ):+ engine.running = True+ assert engine.running is False # setting it has no effect+ engine.downloader.close()++ @coroutine_test+ async def test_spider_closed_callback(self) -> None:+ crawler = get_crawler(DefaultSpider)+ crawler.spider = crawler._create_spider()+ callback = Mock()+ with pytest.warns(ScrapyDeprecationWarning, match="spider_closed_callback"):+ engine = crawler.engine = ExecutionEngine(crawler, callback)+ await engine.open_spider_async()+ await engine.close_spider_async()+ callback.assert_called_once_with(crawler.spider)diff --git a/tests/test_extension_remote_control.py b/tests/test_extension_remote_control.pyindex cddd5e47e..5c0cad507 100644--- a/tests/test_extension_remote_control.py+++ b/tests/test_extension_remote_control.py@@ -553,6 +553,19 @@ async def test_stop_is_idempotent(tmp_path: Path) -> None:assert list(tmp_path.glob("*.json")) == []+@coroutine_test+async def test_stop_during_start(+ tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ extension = _get_extension({"REMOTE_CONTROL_JOBS_DIR": str(tmp_path)})+ with caplog.at_level(logging.INFO):+ await asyncio.gather(extension.start(), extension.stop())+ assert "Remote control HTTP server listening" in caplog.text+ assert not [r for r in caplog.records if r.levelno >= logging.ERROR]+ assert extension._runner is None+ assert list(tmp_path.glob("*.json")) == []++@coroutine_testasync def test_start_failure_disables_the_extension(tmp_path: Path, caplog: pytest.LogCaptureFixture