{
    "file_diffs": [
        {
            "old_file_content": "\"\"\"``tornado.gen`` implements generator-based coroutines.\n\n.. note::\n\n   The \"decorator and generator\" approach in this module is a\n   precursor to native coroutines (using ``async def`` and ``await``)\n   which were introduced in Python 3.5. Applications that do not\n   require compatibility with older versions of Python should use\n   native coroutines instead. Some parts of this module are still\n   useful with native coroutines, notably `multi`, `sleep`,\n   `WaitIterator`, and `with_timeout`. Some of these functions have\n   counterparts in the `asyncio` module which may be used as well,\n   although the two may not necessarily be 100% compatible.\n\nCoroutines provide an easier way to work in an asynchronous\nenvironment than chaining callbacks. Code using coroutines is\ntechnically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, here's a coroutine-based handler:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nAsynchronous functions in Tornado return an ``Awaitable`` or `.Future`;\nyielding this object returns its result.\n\nYou can also yield a list or dict of other yieldable objects, which\nwill be started at the same time and run in parallel; a list or dict\nof results will be returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf ``tornado.platform.twisted`` is imported, it is also possible to\nyield Twisted's ``Deferred`` objects. See the `convert_yielded`\nfunction to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nimport asyncio\nimport builtins\nimport collections\nfrom collections.abc import Generator\nimport concurrent.futures\nimport datetime\nimport functools\nfrom functools import singledispatch\nfrom inspect import isawaitable\nimport sys\nimport types\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n    future_set_result_unless_cancelled,\n)\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado.util import TimeoutError\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\nfrom typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload\n\nif typing.TYPE_CHECKING:\n    from typing import Sequence, Deque, Optional, Set, Iterable  # noqa: F401\n\n_T = typing.TypeVar(\"_T\")\n\n_Yieldable = Union[\n    None, Awaitable, List[Awaitable], Dict[Any, Awaitable], concurrent.futures.Future\n]\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef _value_from_stopiteration(e: Union[StopIteration, \"Return\"]) -> Any:\n    try:\n        # StopIteration has a value attribute beginning in py33.\n        # So does our Return class.\n        return e.value\n    except AttributeError:\n        pass\n    try:\n        # Cython backports coroutine functionality by putting the value in\n        # e.args[0].\n        return e.args[0]\n    except (AttributeError, IndexError):\n        return None\n\n\ndef _create_future() -> Future:\n    future = Future()  # type: Future\n    # Fixup asyncio debug info by removing extraneous stack entries\n    source_traceback = getattr(future, \"_source_traceback\", ())\n    while source_traceback:\n        # Each traceback entry is equivalent to a\n        # (filename, self.lineno, self.name, self.line) tuple\n        filename = source_traceback[-1][0]\n        if filename == __file__:\n            del source_traceback[-1]\n        else:\n            break\n    return future\n\n\ndef _fake_ctx_run(f: Callable[..., _T], *args: Any, **kw: Any) -> _T:\n    return f(*args, **kw)\n\n\n@overload\ndef coroutine(\n    func: Callable[..., \"Generator[Any, Any, _T]\"]\n) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\n@overload\ndef coroutine(func: Callable[..., _T]) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\ndef coroutine(\n    func: Union[Callable[..., \"Generator[Any, Any, _T]\"], Callable[..., _T]]\n) -> Callable[..., \"Future[_T]\"]:\n    \"\"\"Decorator for asynchronous generators.\n\n    For compatibility with older versions of Python, coroutines may\n    also \"return\" by raising the special exception `Return(value)\n    <Return>`.\n\n    Functions with this decorator return a `.Future`.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed. Use the returned\n       awaitable object instead.\n\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        # type: (*Any, **Any) -> Future[_T]\n        # This function is type-annotated with a comment to work around\n        # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in\n        future = _create_future()\n        if contextvars is not None:\n            ctx_run = contextvars.copy_context().run  # type: Callable\n        else:\n            ctx_run = _fake_ctx_run\n        try:\n            result = ctx_run(func, *args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = _value_from_stopiteration(e)\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n            try:\n                return future\n            finally:\n                # Avoid circular references\n                future = None  # type: ignore\n        else:\n            if isinstance(result, Generator):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    yielded = ctx_run(next, result)\n                except (StopIteration, Return) as e:\n                    future_set_result_unless_cancelled(\n                        future, _value_from_stopiteration(e)\n                    )\n                except Exception:\n                    future_set_exc_info(future, sys.exc_info())\n                else:\n                    # Provide strong references to Runner objects as long\n                    # as their result future objects also have strong\n                    # references (typically from the parent coroutine's\n                    # Runner). This keeps the coroutine's Runner alive.\n                    # We do this by exploiting the public API\n                    # add_done_callback() instead of putting a private\n                    # attribute on the Future.\n                    # (GitHub issues #1769, #2229).\n                    runner = Runner(ctx_run, result, future, yielded)\n                    future.add_done_callback(lambda _: runner)\n                yielded = None\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None  # type: ignore\n        future_set_result_unless_cancelled(future, result)\n        return future\n\n    wrapper.__wrapped__ = func  # type: ignore\n    wrapper.__tornado_coroutine__ = True  # type: ignore\n    return wrapper\n\n\ndef is_coroutine_function(func: Any) -> bool:\n    \"\"\"Return whether *func* is a coroutine function, i.e. a function\n    wrapped with `~.gen.coroutine`.\n\n    .. versionadded:: 4.5\n    \"\"\"\n    return getattr(func, \"__tornado_coroutine__\", False)\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n\n    def __init__(self, value: Any = None) -> None:\n        super().__init__()\n        self.value = value\n        # Cython recognizes subclasses of StopIteration with a .args tuple.\n        self.args = (value,)\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of awaitables as they finish.\n\n    Yielding a set of awaitables like this:\n\n    ``results = yield [awaitable1, awaitable2]``\n\n    pauses the coroutine until both ``awaitable1`` and ``awaitable2``\n    return, and then restarts the coroutine with the results of both\n    awaitables. If either awaitable raises an exception, the\n    expression will raise that exception and all the results will be\n    lost.\n\n    If you need to get the result of each awaitable as soon as possible,\n    or if you need the result of some awaitables even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(awaitable1, awaitable2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} received from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the awaitable from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    On Python 3.5, `WaitIterator` implements the async iterator\n    protocol, so it can be used with the ``async for`` statement (note\n    that in this version the entire iteration is aborted if any value\n    raises an exception, while the previous example can continue past\n    individual errors)::\n\n      async for result in gen.WaitIterator(future1, future2):\n          print(\"Result {} received from {} at {}\".format(\n              result, wait_iterator.current_future,\n              wait_iterator.current_index))\n\n    .. versionadded:: 4.1\n\n    .. versionchanged:: 4.3\n       Added ``async for`` support in Python 3.5.\n\n    \"\"\"\n\n    _unfinished = {}  # type: Dict[Future, Union[int, str]]\n\n    def __init__(self, *args: Future, **kwargs: Future) -> None:\n        if args and kwargs:\n            raise ValueError(\"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())  # type: Sequence[Future]\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()  # type: Deque[Future]\n        self.current_index = None  # type: Optional[Union[str, int]]\n        self.current_future = None  # type: Optional[Future]\n        self._running_future = None  # type: Optional[Future]\n\n        for future in futures:\n            future_add_done_callback(future, self._done_callback)\n\n    def done(self) -> bool:\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self) -> Future:\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = Future()\n\n        if self._finished:\n            return self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    def _done_callback(self, done: Future) -> None:\n        if self._running_future and not self._running_future.done():\n            self._return_result(done)\n        else:\n            self._finished.append(done)\n\n    def _return_result(self, done: Future) -> Future:\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        if self._running_future is None:\n            raise Exception(\"no future is running\")\n        chain_future(done, self._running_future)\n\n        res = self._running_future\n        self._running_future = None\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n        return res\n\n    def __aiter__(self) -> typing.AsyncIterator:\n        return self\n\n    def __anext__(self) -> Future:\n        if self.done():\n            # Lookup by name to silence pyflakes on older versions.\n            raise getattr(builtins, \"StopAsyncIteration\")()\n        return self.next()\n\n\ndef multi(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    ``children`` may either be a list or a dict whose values are\n    yieldable objects. ``multi()`` returns a new yieldable\n    object that resolves to a parallel structure containing their\n    results. If ``children`` is a list, the result is a list of\n    results in the same order; if it is a dict, the result is a dict\n    with the same keys.\n\n    That is, ``results = yield multi(list_of_futures)`` is equivalent\n    to::\n\n        results = []\n        for future in list_of_futures:\n            results.append(yield future)\n\n    If any children raise exceptions, ``multi()`` will raise the first\n    one. All others will be logged, unless they are of types\n    contained in the ``quiet_exceptions`` argument.\n\n    In a ``yield``-based coroutine, it is not normally necessary to\n    call this function directly, since the coroutine runner will\n    do it automatically when a list or dict is yielded. However,\n    it is necessary in ``await``-based coroutines, or to pass\n    the ``quiet_exceptions`` argument.\n\n    This function is available under the names ``multi()`` and ``Multi()``\n    for historical reasons.\n\n    Cancelling a `.Future` returned by ``multi()`` does not cancel its\n    children. `asyncio.gather` is similar to ``multi()``, but it does\n    cancel its children.\n\n    .. versionchanged:: 4.2\n       If multiple yieldables fail, any exceptions after the first\n       (which is raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. versionchanged:: 4.3\n       Replaced the class ``Multi`` and the function ``multi_future``\n       with a unified function ``multi``. Added support for yieldables\n       other than ``YieldPoint`` and `.Future`.\n\n    \"\"\"\n    return multi_future(children, quiet_exceptions=quiet_exceptions)\n\n\nMulti = multi\n\n\ndef multi_future(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Since Tornado 6.0, this function is exactly the same as `multi`.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.2\n       If multiple ``Futures`` fail, any exceptions after the first (which is\n       raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. deprecated:: 4.3\n       Use `multi` instead.\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())  # type: Optional[List]\n        children_seq = children.values()  # type: Iterable\n    else:\n        keys = None\n        children_seq = children\n    children_futs = list(map(convert_yielded, children_seq))\n    assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs)\n    unfinished_children = set(children_futs)\n\n    future = _create_future()\n    if not children_futs:\n        future_set_result_unless_cancelled(future, {} if keys is not None else [])\n\n    def callback(fut: Future) -> None:\n        unfinished_children.remove(fut)\n        if not unfinished_children:\n            result_list = []\n            for f in children_futs:\n                try:\n                    result_list.append(f.result())\n                except Exception as e:\n                    if future.done():\n                        if not isinstance(e, quiet_exceptions):\n                            app_log.error(\n                                \"Multiple exceptions in yield list\", exc_info=True\n                            )\n                    else:\n                        future_set_exc_info(future, sys.exc_info())\n            if not future.done():\n                if keys is not None:\n                    future_set_result_unless_cancelled(\n                        future, dict(zip(keys, result_list))\n                    )\n                else:\n                    future_set_result_unless_cancelled(future, result_list)\n\n    listening = set()  # type: Set[Future]\n    for f in children_futs:\n        if f not in listening:\n            listening.add(f)\n            future_add_done_callback(f, callback)\n    return future\n\n\ndef maybe_future(x: Any) -> Future:\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n\n    .. deprecated:: 4.3\n       This function only handles ``Futures``, not other yieldable objects.\n       Instead of `maybe_future`, check for the non-future result types\n       you expect (often just ``None``), and ``yield`` anything unknown.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = _create_future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(\n    timeout: Union[float, datetime.timedelta],\n    future: _Yieldable,\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> Future:\n    \"\"\"Wraps a `.Future` (or other yieldable object) in a timeout.\n\n    Raises `tornado.util.TimeoutError` if the input future does not\n    complete before ``timeout``, which may be specified in any form\n    allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or\n    an absolute time relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is either of a type contained in\n    ``quiet_exceptions`` (which may be an exception type or a sequence of\n    types), or an ``asyncio.CancelledError``.\n\n    The wrapped `.Future` is not canceled when the timeout expires,\n    permitting it to be reused. `asyncio.wait_for` is similar to this\n    function but it does cancel the wrapped `.Future` on timeout.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n\n    .. versionchanged:: 4.4\n       Added support for yieldable objects other than `.Future`.\n\n    .. versionchanged:: 6.0.3\n       ``asyncio.CancelledError`` is now always considered \"quiet\".\n\n    .. versionchanged:: 6.2\n       ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n\n    \"\"\"\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    future_converted = convert_yielded(future)\n    result = _create_future()\n    chain_future(future_converted, result)\n    io_loop = IOLoop.current()\n\n    def error_callback(future: Future) -> None:\n        try:\n            future.result()\n        except asyncio.CancelledError:\n            pass\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\n                    \"Exception in Future %r after timeout\", future, exc_info=True\n                )\n\n    def timeout_callback() -> None:\n        if not result.done():\n            result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future_add_done_callback(future_converted, error_callback)\n\n    timeout_handle = io_loop.add_timeout(timeout, timeout_callback)\n    if isinstance(future_converted, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future_add_done_callback(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    return result\n\n\ndef sleep(duration: float) -> \"Future[None]\":\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = _create_future()\n    IOLoop.current().call_later(\n        duration, lambda: future_set_result_unless_cancelled(f, None)\n    )\n    return f\n\n\nclass _NullFuture(object):\n    \"\"\"_NullFuture resembles a Future that finished with a result of None.\n\n    It's not actually a `Future` to avoid depending on a particular event loop.\n    Handled as a special case in the coroutine runner.\n\n    We lie and tell the type checker that a _NullFuture is a Future so\n    we don't have to leak _NullFuture into lots of public APIs. But\n    this means that the type checker can't warn us when we're passing\n    a _NullFuture into a code path that doesn't understand what to do\n    with it.\n    \"\"\"\n\n    def result(self) -> None:\n        return None\n\n    def done(self) -> bool:\n        return True\n\n\n# _null_future is used as a dummy value in the coroutine runner. It differs\n# from moment in that moment always adds a delay of one IOLoop iteration\n# while _null_future is processed as soon as possible.\n_null_future = typing.cast(Future, _NullFuture())\n\nmoment = typing.cast(Future, _NullFuture())\nmoment.__doc__ = \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\nIn native coroutines, the equivalent of ``yield gen.moment`` is\n``await asyncio.sleep(0)``.\n\n.. versionadded:: 4.0\n\n.. deprecated:: 4.5\n   ``yield None`` (or ``yield`` with no argument) is now equivalent to\n    ``yield gen.moment``.\n\"\"\"\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.handle_yield(first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False\n\n\n# Convert Awaitables into Futures.\ntry:\n    _wrap_awaitable = asyncio.ensure_future\nexcept AttributeError:\n    # asyncio.ensure_future was introduced in Python 3.4.4, but\n    # Debian jessie still ships with 3.4.2 so try the old name.\n    _wrap_awaitable = getattr(asyncio, \"async\")\n\n\ndef convert_yielded(yielded: _Yieldable) -> Future:\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and\n    Futures. This has the side effect of starting any coroutines that\n    did not start themselves, similar to `asyncio.ensure_future`.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n\n    \"\"\"\n    if yielded is None or yielded is moment:\n        return moment\n    elif yielded is _null_future:\n        return _null_future\n    elif isinstance(yielded, (list, dict)):\n        return multi(yielded)  # type: ignore\n    elif is_future(yielded):\n        return typing.cast(Future, yielded)\n    elif isawaitable(yielded):\n        return _wrap_awaitable(yielded)  # type: ignore\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\n\nconvert_yielded = singledispatch(convert_yielded)\n",
            "new_file_content": "\"\"\"``tornado.gen`` implements generator-based coroutines.\n\n.. note::\n\n   The \"decorator and generator\" approach in this module is a\n   precursor to native coroutines (using ``async def`` and ``await``)\n   which were introduced in Python 3.5. Applications that do not\n   require compatibility with older versions of Python should use\n   native coroutines instead. Some parts of this module are still\n   useful with native coroutines, notably `multi`, `sleep`,\n   `WaitIterator`, and `with_timeout`. Some of these functions have\n   counterparts in the `asyncio` module which may be used as well,\n   although the two may not necessarily be 100% compatible.\n\nCoroutines provide an easier way to work in an asynchronous\nenvironment than chaining callbacks. Code using coroutines is\ntechnically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, here's a coroutine-based handler:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nAsynchronous functions in Tornado return an ``Awaitable`` or `.Future`;\nyielding this object returns its result.\n\nYou can also yield a list or dict of other yieldable objects, which\nwill be started at the same time and run in parallel; a list or dict\nof results will be returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf ``tornado.platform.twisted`` is imported, it is also possible to\nyield Twisted's ``Deferred`` objects. See the `convert_yielded`\nfunction to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nimport asyncio\nimport builtins\nimport collections\nfrom collections.abc import Generator\nimport concurrent.futures\nimport datetime\nimport functools\nfrom functools import singledispatch\nfrom inspect import isawaitable\nimport sys\nimport types\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n    future_set_result_unless_cancelled,\n)\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado.util import TimeoutError\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\nfrom typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload\n\nif typing.TYPE_CHECKING:\n    from typing import Sequence, Deque, Optional, Set, Iterable  # noqa: F401\n\n_T = typing.TypeVar(\"_T\")\n\n_Yieldable = Union[\n    None, Awaitable, List[Awaitable], Dict[Any, Awaitable], concurrent.futures.Future\n]\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef _value_from_stopiteration(e: Union[StopIteration, \"Return\"]) -> Any:\n    try:\n        # StopIteration has a value attribute beginning in py33.\n        # So does our Return class.\n        return e.value\n    except AttributeError:\n        pass\n    try:\n        # Cython backports coroutine functionality by putting the value in\n        # e.args[0].\n        return e.args[0]\n    except (AttributeError, IndexError):\n        return None\n\n\ndef _create_future() -> Future:\n    future = Future()  # type: Future\n    # Fixup asyncio debug info by removing extraneous stack entries\n    source_traceback = getattr(future, \"_source_traceback\", ())\n    while source_traceback:\n        # Each traceback entry is equivalent to a\n        # (filename, self.lineno, self.name, self.line) tuple\n        filename = source_traceback[-1][0]\n        if filename == __file__:\n            del source_traceback[-1]\n        else:\n            break\n    return future\n\n\ndef _fake_ctx_run(f: Callable[..., _T], *args: Any, **kw: Any) -> _T:\n    return f(*args, **kw)\n\n\n@overload\ndef coroutine(\n    func: Callable[..., \"Generator[Any, Any, _T]\"]\n) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\n@overload\ndef coroutine(func: Callable[..., _T]) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\ndef coroutine(\n    func: Union[Callable[..., \"Generator[Any, Any, _T]\"], Callable[..., _T]]\n) -> Callable[..., \"Future[_T]\"]:\n    \"\"\"Decorator for asynchronous generators.\n\n    For compatibility with older versions of Python, coroutines may\n    also \"return\" by raising the special exception `Return(value)\n    <Return>`.\n\n    Functions with this decorator return a `.Future`.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed. Use the returned\n       awaitable object instead.\n\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        # type: (*Any, **Any) -> Future[_T]\n        # This function is type-annotated with a comment to work around\n        # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in\n        future = _create_future()\n        if contextvars is not None:\n            ctx_run = contextvars.copy_context().run  # type: Callable\n        else:\n            ctx_run = _fake_ctx_run\n        try:\n            result = ctx_run(func, *args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = _value_from_stopiteration(e)\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n            try:\n                return future\n            finally:\n                # Avoid circular references\n                future = None  # type: ignore\n        else:\n            if isinstance(result, Generator):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    yielded = ctx_run(next, result)\n                except (StopIteration, Return) as e:\n                    future_set_result_unless_cancelled(\n                        future, _value_from_stopiteration(e)\n                    )\n                except Exception:\n                    future_set_exc_info(future, sys.exc_info())\n                else:\n                    # Provide strong references to Runner objects as long\n                    # as their result future objects also have strong\n                    # references (typically from the parent coroutine's\n                    # Runner). This keeps the coroutine's Runner alive.\n                    # We do this by exploiting the public API\n                    # add_done_callback() instead of putting a private\n                    # attribute on the Future.\n                    # (GitHub issues #1769, #2229).\n                    runner = Runner(ctx_run, result, future, yielded)\n                    future.add_done_callback(lambda _: runner)\n                yielded = None\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None  # type: ignore\n        future_set_result_unless_cancelled(future, result)\n        return future\n\n    wrapper.__wrapped__ = func  # type: ignore\n    wrapper.__tornado_coroutine__ = True  # type: ignore\n    return wrapper\n\n\ndef is_coroutine_function(func: Any) -> bool:\n    \"\"\"Return whether *func* is a coroutine function, i.e. a function\n    wrapped with `~.gen.coroutine`.\n\n    .. versionadded:: 4.5\n    \"\"\"\n    return getattr(func, \"__tornado_coroutine__\", False)\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n\n    def __init__(self, value: Any = None) -> None:\n        super().__init__()\n        self.value = value\n        # Cython recognizes subclasses of StopIteration with a .args tuple.\n        self.args = (value,)\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of awaitables as they finish.\n\n    Yielding a set of awaitables like this:\n\n    ``results = yield [awaitable1, awaitable2]``\n\n    pauses the coroutine until both ``awaitable1`` and ``awaitable2``\n    return, and then restarts the coroutine with the results of both\n    awaitables. If either awaitable raises an exception, the\n    expression will raise that exception and all the results will be\n    lost.\n\n    If you need to get the result of each awaitable as soon as possible,\n    or if you need the result of some awaitables even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(awaitable1, awaitable2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} received from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the awaitable from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    On Python 3.5, `WaitIterator` implements the async iterator\n    protocol, so it can be used with the ``async for`` statement (note\n    that in this version the entire iteration is aborted if any value\n    raises an exception, while the previous example can continue past\n    individual errors)::\n\n      async for result in gen.WaitIterator(future1, future2):\n          print(\"Result {} received from {} at {}\".format(\n              result, wait_iterator.current_future,\n              wait_iterator.current_index))\n\n    .. versionadded:: 4.1\n\n    .. versionchanged:: 4.3\n       Added ``async for`` support in Python 3.5.\n\n    \"\"\"\n\n    _unfinished = {}  # type: Dict[Future, Union[int, str]]\n\n    def __init__(self, *args: Future, **kwargs: Future) -> None:\n        if args and kwargs:\n            raise ValueError(\"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())  # type: Sequence[Future]\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()  # type: Deque[Future]\n        self.current_index = None  # type: Optional[Union[str, int]]\n        self.current_future = None  # type: Optional[Future]\n        self._running_future = None  # type: Optional[Future]\n\n        for future in futures:\n            future_add_done_callback(future, self._done_callback)\n\n    def done(self) -> bool:\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self) -> Future:\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = Future()\n\n        if self._finished:\n            return self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    def _done_callback(self, done: Future) -> None:\n        if self._running_future and not self._running_future.done():\n            self._return_result(done)\n        else:\n            self._finished.append(done)\n\n    def _return_result(self, done: Future) -> Future:\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        if self._running_future is None:\n            raise Exception(\"no future is running\")\n        chain_future(done, self._running_future)\n\n        res = self._running_future\n        self._running_future = None\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n        return res\n\n    def __aiter__(self) -> typing.AsyncIterator:\n        return self\n\n    def __anext__(self) -> Future:\n        if self.done():\n            # Lookup by name to silence pyflakes on older versions.\n            raise getattr(builtins, \"StopAsyncIteration\")()\n        return self.next()\n\n\ndef multi(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    ``children`` may either be a list or a dict whose values are\n    yieldable objects. ``multi()`` returns a new yieldable\n    object that resolves to a parallel structure containing their\n    results. If ``children`` is a list, the result is a list of\n    results in the same order; if it is a dict, the result is a dict\n    with the same keys.\n\n    That is, ``results = yield multi(list_of_futures)`` is equivalent\n    to::\n\n        results = []\n        for future in list_of_futures:\n            results.append(yield future)\n\n    If any children raise exceptions, ``multi()`` will raise the first\n    one. All others will be logged, unless they are of types\n    contained in the ``quiet_exceptions`` argument.\n\n    In a ``yield``-based coroutine, it is not normally necessary to\n    call this function directly, since the coroutine runner will\n    do it automatically when a list or dict is yielded. However,\n    it is necessary in ``await``-based coroutines, or to pass\n    the ``quiet_exceptions`` argument.\n\n    This function is available under the names ``multi()`` and ``Multi()``\n    for historical reasons.\n\n    Cancelling a `.Future` returned by ``multi()`` does not cancel its\n    children. `asyncio.gather` is similar to ``multi()``, but it does\n    cancel its children.\n\n    .. versionchanged:: 4.2\n       If multiple yieldables fail, any exceptions after the first\n       (which is raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. versionchanged:: 4.3\n       Replaced the class ``Multi`` and the function ``multi_future``\n       with a unified function ``multi``. Added support for yieldables\n       other than ``YieldPoint`` and `.Future`.\n\n    \"\"\"\n    return multi_future(children, quiet_exceptions=quiet_exceptions)\n\n\nMulti = multi\n\n\ndef multi_future(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Since Tornado 6.0, this function is exactly the same as `multi`.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.2\n       If multiple ``Futures`` fail, any exceptions after the first (which is\n       raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. deprecated:: 4.3\n       Use `multi` instead.\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())  # type: Optional[List]\n        children_seq = children.values()  # type: Iterable\n    else:\n        keys = None\n        children_seq = children\n    children_futs = list(map(convert_yielded, children_seq))\n    assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs)\n    unfinished_children = set(children_futs)\n\n    future = _create_future()\n    if not children_futs:\n        future_set_result_unless_cancelled(future, {} if keys is not None else [])\n\n    def callback(fut: Future) -> None:\n        unfinished_children.remove(fut)\n        if not unfinished_children:\n            result_list = []\n            for f in children_futs:\n                try:\n                    result_list.append(f.result())\n                except Exception as e:\n                    if future.done():\n                        if not isinstance(e, quiet_exceptions):\n                            app_log.error(\n                                \"Multiple exceptions in yield list\", exc_info=True\n                            )\n                    else:\n                        future_set_exc_info(future, sys.exc_info())\n            if not future.done():\n                if keys is not None:\n                    future_set_result_unless_cancelled(\n                        future, dict(zip(keys, result_list))\n                    )\n                else:\n                    future_set_result_unless_cancelled(future, result_list)\n\n    listening = set()  # type: Set[Future]\n    for f in children_futs:\n        if f not in listening:\n            listening.add(f)\n            future_add_done_callback(f, callback)\n    return future\n\n\ndef maybe_future(x: Any) -> Future:\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n\n    .. deprecated:: 4.3\n       This function only handles ``Futures``, not other yieldable objects.\n       Instead of `maybe_future`, check for the non-future result types\n       you expect (often just ``None``), and ``yield`` anything unknown.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = _create_future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(\n    timeout: Union[float, datetime.timedelta],\n    future: _Yieldable,\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> Future:\n    \"\"\"Wraps a `.Future` (or other yieldable object) in a timeout.\n\n    Raises `tornado.util.TimeoutError` if the input future does not\n    complete before ``timeout``, which may be specified in any form\n    allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or\n    an absolute time relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is either of a type contained in\n    ``quiet_exceptions`` (which may be an exception type or a sequence of\n    types), or an ``asyncio.CancelledError``.\n\n    The wrapped `.Future` is not canceled when the timeout expires,\n    permitting it to be reused. `asyncio.wait_for` is similar to this\n    function but it does cancel the wrapped `.Future` on timeout.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n\n    .. versionchanged:: 4.4\n       Added support for yieldable objects other than `.Future`.\n\n    .. versionchanged:: 6.0.3\n       ``asyncio.CancelledError`` is now always considered \"quiet\".\n\n    .. versionchanged:: 6.2\n       ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n\n    \"\"\"\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    future_converted = convert_yielded(future)\n    result = _create_future()\n    chain_future(future_converted, result)\n    io_loop = IOLoop.current()\n\n    def error_callback(future: Future) -> None:\n        try:\n            future.result()\n        except asyncio.CancelledError:\n            pass\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\n                    \"Exception in Future %r after timeout\", future, exc_info=True\n                )\n\n    def timeout_callback() -> None:\n        if not result.done():\n            result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future_add_done_callback(future_converted, error_callback)\n\n    timeout_handle = io_loop.add_timeout(timeout, timeout_callback)\n    if isinstance(future_converted, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future_add_done_callback(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    return result\n\n\ndef sleep(duration: float) -> \"Future[None]\":\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = _create_future()\n    IOLoop.current().call_later(\n        duration, lambda: future_set_result_unless_cancelled(f, None)\n    )\n    return f\n\n\nclass _NullFuture(object):\n    \"\"\"_NullFuture resembles a Future that finished with a result of None.\n\n    It's not actually a `Future` to avoid depending on a particular event loop.\n    Handled as a special case in the coroutine runner.\n\n    We lie and tell the type checker that a _NullFuture is a Future so\n    we don't have to leak _NullFuture into lots of public APIs. But\n    this means that the type checker can't warn us when we're passing\n    a _NullFuture into a code path that doesn't understand what to do\n    with it.\n    \"\"\"\n\n    def result(self) -> None:\n        return None\n\n    def done(self) -> bool:\n        return True\n\n\n# _null_future is used as a dummy value in the coroutine runner. It differs\n# from moment in that moment always adds a delay of one IOLoop iteration\n# while _null_future is processed as soon as possible.\n_null_future = typing.cast(Future, _NullFuture())\n\nmoment = typing.cast(Future, _NullFuture())\nmoment.__doc__ = \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\nIn native coroutines, the equivalent of ``yield gen.moment`` is\n``await asyncio.sleep(0)``.\n\n.. versionadded:: 4.0\n\n.. deprecated:: 4.5\n   ``yield None`` (or ``yield`` with no argument) is now equivalent to\n    ``yield gen.moment``.\n\"\"\"\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.ctx_run(self.handle_yield, first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False\n\n\n# Convert Awaitables into Futures.\ntry:\n    _wrap_awaitable = asyncio.ensure_future\nexcept AttributeError:\n    # asyncio.ensure_future was introduced in Python 3.4.4, but\n    # Debian jessie still ships with 3.4.2 so try the old name.\n    _wrap_awaitable = getattr(asyncio, \"async\")\n\n\ndef convert_yielded(yielded: _Yieldable) -> Future:\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and\n    Futures. This has the side effect of starting any coroutines that\n    did not start themselves, similar to `asyncio.ensure_future`.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n\n    \"\"\"\n    if yielded is None or yielded is moment:\n        return moment\n    elif yielded is _null_future:\n        return _null_future\n    elif isinstance(yielded, (list, dict)):\n        return multi(yielded)  # type: ignore\n    elif is_future(yielded):\n        return typing.cast(Future, yielded)\n    elif isawaitable(yielded):\n        return _wrap_awaitable(yielded)  # type: ignore\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\n\nconvert_yielded = singledispatch(convert_yielded)\n",
            "header": {
                "file": {
                    "path": "tornado/gen.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1946ab91",
                "new_commit_hash": "f3e6e72f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/gen.py"
            },
            "plus_file": {
                "path": "b/tornado/gen.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 743,
                            "length": 7
                        },
                        "new_range": {
                            "start": 743,
                            "length": 7
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.running = False",
                                "type": "context"
                            },
                            {
                                "content": "        self.finished = False",
                                "type": "context"
                            },
                            {
                                "content": "        self.io_loop = IOLoop.current()",
                                "type": "context"
                            },
                            {
                                "content": "        if self.handle_yield(first_yielded):",
                                "type": "deleted"
                            },
                            {
                                "content": "        if self.ctx_run(self.handle_yield, first_yielded):",
                                "type": "added"
                            },
                            {
                                "content": "            gen = result_future = first_yielded = None  # type: ignore",
                                "type": "context"
                            },
                            {
                                "content": "            self.ctx_run(self.run)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Runner.__init__",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.handle_yield(first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 732,
                            "end_lineno": 748,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Runner",
                                "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.handle_yield(first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 723,
                                "end_lineno": 836,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Runner",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.handle_yield(first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 723,
                            "end_lineno": 836,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nfrom concurrent import futures\nimport gc\nimport datetime\nimport platform\nimport sys\nimport time\nimport weakref\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import skipOnTravis, skipNotCPython\nfrom tornado.web import Application, RequestHandler, HTTPError\n\nfrom tornado import gen\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List, Optional  # noqa: F401\n\n\nclass GenBasicTest(AsyncTestCase):\n    @gen.coroutine\n    def delay(self, iterations, arg):\n        \"\"\"Returns arg after a number of IOLoop iterations.\"\"\"\n        for i in range(iterations):\n            yield gen.moment\n        raise gen.Return(arg)\n\n    @gen.coroutine\n    def async_future(self, result):\n        yield gen.moment\n        return result\n\n    @gen.coroutine\n    def async_exception(self, e):\n        yield gen.moment\n        raise e\n\n    @gen.coroutine\n    def add_one_async(self, x):\n        yield gen.moment\n        raise gen.Return(x + 1)\n\n    def test_no_yield(self):\n        @gen.coroutine\n        def f():\n            pass\n\n        self.io_loop.run_sync(f)\n\n    def test_exception_phase1(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_exception_phase2(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield(self):\n        @gen.coroutine\n        def f():\n            yield 42\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.coroutine\n        def f():\n            yield (1, 2)\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_reuse(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n\n        self.io_loop.run_sync(f)\n        self.io_loop.run_sync(f)\n\n    def test_none(self):\n        @gen.coroutine\n        def f():\n            yield None\n\n        self.io_loop.run_sync(f)\n\n    def test_multi(self):\n        @gen.coroutine\n        def f():\n            results = yield [self.add_one_async(1), self.add_one_async(2)]\n            self.assertEqual(results, [2, 3])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict(self):\n        @gen.coroutine\n        def f():\n            results = yield dict(foo=self.add_one_async(1), bar=self.add_one_async(2))\n            self.assertEqual(results, dict(foo=2, bar=3))\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                [self.delay(3, \"v1\"), self.delay(1, \"v2\")]\n            )\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                dict(foo=self.delay(3, \"v1\"), bar=self.delay(1, \"v2\"))\n            )\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n\n        self.io_loop.run_sync(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.moment for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_future_duplicate(self):\n        # Note that this doesn't work with native corotines, only with\n        # decorated coroutines.\n        f = self.async_future(2)\n        results = yield [self.async_future(1), f, self.async_future(3), f]\n        self.assertEqual(results, [1, 2, 3, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    @gen_test\n    def test_multi_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield gen.Multi(\n                    [\n                        self.async_exception(RuntimeError(\"error 1\")),\n                        self.async_exception(RuntimeError(\"error 2\")),\n                    ]\n                )\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n            )\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    @gen_test\n    def test_multi_future_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ]\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.multi_future(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    def test_sync_raise_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_async_raise_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_sync_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super().setUp()\n\n    def tearDown(self):\n        super().tearDown()\n        assert self.finished\n\n    def test_attributes(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertEqual(coro.__name__, f.__name__)\n        self.assertEqual(coro.__module__, f.__module__)\n        self.assertIs(coro.__wrapped__, f)  # type: ignore\n\n    def test_is_coroutine_function(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertFalse(gen.is_coroutine_function(f))\n        self.assertTrue(gen.is_coroutine_function(coro))\n        self.assertFalse(gen.is_coroutine_function(coro()))\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n            raise gen.Return(42)\n\n        # This test verifies that an async function can await a\n        # yield-based gen.coroutine, and that a gen.coroutine\n        # (the test method itself) can yield an async function.\n        async def f2():\n            result = await f1()\n            return result\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_asyncio_sleep_zero(self):\n        # asyncio.sleep(0) turns into a special case (equivalent to\n        # `yield None`)\n        async def f():\n            import asyncio\n\n            await asyncio.sleep(0)\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await_mixed_multi_native_future(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n            return 42\n\n        @gen.coroutine\n        def f3():\n            yield gen.moment\n            raise gen.Return(43)\n\n        results = yield [f2(), f3()]\n        self.assertEqual(results, [42, 43])\n        self.finished = True\n\n    @gen_test\n    def test_async_with_timeout(self):\n        async def f1():\n            return 42\n\n        result = yield gen.with_timeout(datetime.timedelta(hours=1), f1())\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()  # type: Future[None]\n        immediate.set_result(None)\n        yield [f(\"a\", immediate), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"aaaaabbbbb\")\n\n        # With moment, they take turns.\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", gen.moment)]\n        self.assertEqual(\"\".join(calls), \"ababababab\")\n        self.finished = True\n\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"abbbbbaaaa\")\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True\n\n    @skipNotCPython\n    @unittest.skipIf(\n        (3,) < sys.version_info < (3, 6), \"asyncio.Future has reference cycles\"\n    )\n    def test_coroutine_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.coroutine\n        def inner():\n            class Foo(object):\n                pass\n\n            local_var = Foo()\n            self.local_ref = weakref.ref(local_var)\n\n            def dummy():\n                pass\n\n            yield gen.coroutine(dummy)()\n            raise ValueError(\"Some error\")\n\n        @gen.coroutine\n        def inner2():\n            try:\n                yield inner()\n            except ValueError:\n                pass\n\n        self.io_loop.run_sync(inner2, timeout=3)\n\n        self.assertIs(self.local_ref(), None)\n        self.finished = True\n\n    def test_asyncio_future_debug_info(self):\n        self.finished = True\n        # Enable debug mode\n        asyncio_loop = asyncio.get_event_loop()\n        self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug())\n        asyncio_loop.set_debug(True)\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)()\n        self.assertIsInstance(coro, asyncio.Future)\n        # We expect the coroutine repr() to show the place where\n        # it was instantiated\n        expected = \"created at %s:%d\" % (__file__, f.__code__.co_firstlineno + 3)\n        actual = repr(coro)\n        self.assertIn(expected, actual)\n\n    @gen_test\n    def test_asyncio_gather(self):\n        # This demonstrates that tornado coroutines can be understood\n        # by asyncio (This failed prior to Tornado 5.0).\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(1)\n\n        ret = yield asyncio.gather(f(), f())\n        self.assertEqual(ret, [1, 1])\n        self.finished = True\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        # just write, don't finish\n        self.write(\"3\")\n\n\n# \"Undecorated\" here refers to the absence of @asynchronous.\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []  # type: List[str]\n        yield gen.moment\n        self.chunks.append(\"1\")\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append(\"2\")\n        yield gen.moment\n        self.chunks.append(\"3\")\n        yield gen.moment\n        self.write(\"\".join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish(\"ok\")\n\n\nclass NativeCoroutineHandler(RequestHandler):\n    async def get(self):\n        await asyncio.sleep(0)\n        self.write(\"ok\")\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                (\"/coroutine_sequence\", GenCoroutineSequenceHandler),\n                (\n                    \"/coroutine_unfinished_sequence\",\n                    GenCoroutineUnfinishedSequenceHandler,\n                ),\n                (\"/undecorated_coroutine\", UndecoratedCoroutinesHandler),\n                (\"/async_prepare_error\", AsyncPrepareErrorHandler),\n                (\"/native_coroutine\", NativeCoroutineHandler),\n            ]\n        )\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch(\"/coroutine_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch(\"/coroutine_unfinished_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch(\"/undecorated_coroutine\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch(\"/async_prepare_error\")\n        self.assertEqual(response.code, 403)\n\n    def test_native_coroutine_handler(self):\n        response = self.fetch(\"/native_coroutine\")\n        self.assertEqual(response.code, 200)\n        self.assertEqual(response.body, b\"ok\")\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1), lambda: future.set_result(\"asdf\")\n        )\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()),\n        )\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()  # type: Future[str]\n        future.set_result(\"asdf\")\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        # A concurrent future that does not resolve before the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(\n                    self.io_loop.time(), executor.submit(time.sleep, 0.1)\n                )\n\n    @gen_test\n    def test_completed_concurrent_future(self):\n        # A concurrent future that is resolved before we even submit it\n        # to with_timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n\n            def dummy():\n                pass\n\n            f = executor.submit(dummy)\n            f.result()  # wait for completion\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), f)\n\n    @gen_test\n    def test_normal_concurrent_future(self):\n        # A conccurrent future that resolves while waiting for the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(\n                datetime.timedelta(seconds=3600),\n                executor.submit(lambda: time.sleep(0.01)),\n            )\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), \"empty generator iterated\")\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(Future(), bar=Future())\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()  # type: Future[int]\n        f2 = Future()  # type: Future[int]\n        f3 = Future()  # type: Future[int]\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(\n                    dg.current_future == f1 and dr == 24,\n                    \"WaitIterator dict status incorrect\",\n                )\n            elif dg.current_index == \"f2\":\n                self.assertTrue(\n                    dg.current_future == f2 and dr == 42,\n                    \"WaitIterator dict status incorrect\",\n                )\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0], \"exception future invalid\")\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 2, \"wrong index\")\n                elif i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n            i += 1\n\n    @gen_test\n    def test_iterator_async_await(self):\n        # Recreate the previous test with py35 syntax. It's a little clunky\n        # because of the way the previous test handles an exception on\n        # a single iteration.\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n        self.finish_coroutines(0, futures)\n        self.finished = False\n\n        async def f():\n            i = 0\n            g = gen.WaitIterator(*futures)\n            try:\n                async for r in g:\n                    if i == 0:\n                        self.assertEqual(r, 24, \"iterator value incorrect\")\n                        self.assertEqual(g.current_index, 2, \"wrong index\")\n                    else:\n                        raise Exception(\"expected exception on iteration 1\")\n                    i += 1\n            except ZeroDivisionError:\n                i += 1\n            async for r in g:\n                if i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n                else:\n                    raise Exception(\"didn't expect iteration %d\" % i)\n                i += 1\n            self.finished = True\n\n        yield f()\n        self.assertTrue(self.finished)\n\n    @gen_test\n    def test_no_ref(self):\n        # In this usage, there is no direct hard reference to the\n        # WaitIterator itself, only the Future it returns. Since\n        # WaitIterator uses weak references internally to improve GC\n        # performance, this used to cause problems.\n        yield gen.with_timeout(\n            datetime.timedelta(seconds=0.1), gen.WaitIterator(gen.sleep(0)).next()\n        )\n\n\nclass RunnerGCTest(AsyncTestCase):\n    def is_pypy3(self):\n        return platform.python_implementation() == \"PyPy\" and sys.version_info > (3,)\n\n    @gen_test\n    def test_gc(self):\n        # GitHub issue 1769: Runner objects can get GCed unexpectedly\n        # while their future is alive.\n        weakref_scope = [None]  # type: List[Optional[weakref.ReferenceType]]\n\n        def callback():\n            gc.collect(2)\n            weakref_scope[0]().set_result(123)  # type: ignore\n\n        @gen.coroutine\n        def tester():\n            fut = Future()  # type: Future[int]\n            weakref_scope[0] = weakref.ref(fut)\n            self.io_loop.add_callback(callback)\n            yield fut\n\n        yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())\n\n    def test_gc_infinite_coro(self):\n        # GitHub issue 2229: suspended coroutines should be GCed when\n        # their loop is closed, even if they're involved in a reference\n        # cycle.\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def infinite_coro():\n            try:\n                while True:\n                    yield gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        @gen.coroutine\n        def do_something():\n            fut = infinite_coro()\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        loop.close()\n        gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_gc_infinite_async_await(self):\n        # Same as test_gc_infinite_coro, but with a `async def` function\n        import asyncio\n\n        async def infinite_coro(result):\n            try:\n                while True:\n                    await gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def do_something():\n            fut = asyncio.get_event_loop().create_task(infinite_coro(result))\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        with ExpectLog(\"asyncio\", \"Task was destroyed but it is pending\"):\n            loop.close()\n            gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup and one finally\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_multi_moment(self):\n        # Test gen.multi with moment\n        # now that it's not a real Future\n        @gen.coroutine\n        def wait_a_moment():\n            result = yield gen.multi([gen.moment, gen.moment])\n            raise gen.Return(result)\n\n        loop = self.get_new_ioloop()\n        result = loop.run_sync(wait_a_moment)\n        self.assertEqual(result, [None, None])\n\n\nif contextvars is not None:\n    ctx_var = contextvars.ContextVar(\"ctx_var\")  # type: contextvars.ContextVar[int]\n\n\n@unittest.skipIf(contextvars is None, \"contextvars module not present\")\nclass ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "import asyncio\nfrom concurrent import futures\nimport gc\nimport datetime\nimport platform\nimport sys\nimport time\nimport weakref\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import skipOnTravis, skipNotCPython\nfrom tornado.web import Application, RequestHandler, HTTPError\n\nfrom tornado import gen\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List, Optional  # noqa: F401\n\n\nclass GenBasicTest(AsyncTestCase):\n    @gen.coroutine\n    def delay(self, iterations, arg):\n        \"\"\"Returns arg after a number of IOLoop iterations.\"\"\"\n        for i in range(iterations):\n            yield gen.moment\n        raise gen.Return(arg)\n\n    @gen.coroutine\n    def async_future(self, result):\n        yield gen.moment\n        return result\n\n    @gen.coroutine\n    def async_exception(self, e):\n        yield gen.moment\n        raise e\n\n    @gen.coroutine\n    def add_one_async(self, x):\n        yield gen.moment\n        raise gen.Return(x + 1)\n\n    def test_no_yield(self):\n        @gen.coroutine\n        def f():\n            pass\n\n        self.io_loop.run_sync(f)\n\n    def test_exception_phase1(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_exception_phase2(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield(self):\n        @gen.coroutine\n        def f():\n            yield 42\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.coroutine\n        def f():\n            yield (1, 2)\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_reuse(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n\n        self.io_loop.run_sync(f)\n        self.io_loop.run_sync(f)\n\n    def test_none(self):\n        @gen.coroutine\n        def f():\n            yield None\n\n        self.io_loop.run_sync(f)\n\n    def test_multi(self):\n        @gen.coroutine\n        def f():\n            results = yield [self.add_one_async(1), self.add_one_async(2)]\n            self.assertEqual(results, [2, 3])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict(self):\n        @gen.coroutine\n        def f():\n            results = yield dict(foo=self.add_one_async(1), bar=self.add_one_async(2))\n            self.assertEqual(results, dict(foo=2, bar=3))\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                [self.delay(3, \"v1\"), self.delay(1, \"v2\")]\n            )\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                dict(foo=self.delay(3, \"v1\"), bar=self.delay(1, \"v2\"))\n            )\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n\n        self.io_loop.run_sync(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.moment for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_future_duplicate(self):\n        # Note that this doesn't work with native corotines, only with\n        # decorated coroutines.\n        f = self.async_future(2)\n        results = yield [self.async_future(1), f, self.async_future(3), f]\n        self.assertEqual(results, [1, 2, 3, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    @gen_test\n    def test_multi_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield gen.Multi(\n                    [\n                        self.async_exception(RuntimeError(\"error 1\")),\n                        self.async_exception(RuntimeError(\"error 2\")),\n                    ]\n                )\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n            )\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    @gen_test\n    def test_multi_future_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ]\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.multi_future(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    def test_sync_raise_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_async_raise_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_sync_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super().setUp()\n\n    def tearDown(self):\n        super().tearDown()\n        assert self.finished\n\n    def test_attributes(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertEqual(coro.__name__, f.__name__)\n        self.assertEqual(coro.__module__, f.__module__)\n        self.assertIs(coro.__wrapped__, f)  # type: ignore\n\n    def test_is_coroutine_function(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertFalse(gen.is_coroutine_function(f))\n        self.assertTrue(gen.is_coroutine_function(coro))\n        self.assertFalse(gen.is_coroutine_function(coro()))\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n            raise gen.Return(42)\n\n        # This test verifies that an async function can await a\n        # yield-based gen.coroutine, and that a gen.coroutine\n        # (the test method itself) can yield an async function.\n        async def f2():\n            result = await f1()\n            return result\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_asyncio_sleep_zero(self):\n        # asyncio.sleep(0) turns into a special case (equivalent to\n        # `yield None`)\n        async def f():\n            import asyncio\n\n            await asyncio.sleep(0)\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await_mixed_multi_native_future(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n            return 42\n\n        @gen.coroutine\n        def f3():\n            yield gen.moment\n            raise gen.Return(43)\n\n        results = yield [f2(), f3()]\n        self.assertEqual(results, [42, 43])\n        self.finished = True\n\n    @gen_test\n    def test_async_with_timeout(self):\n        async def f1():\n            return 42\n\n        result = yield gen.with_timeout(datetime.timedelta(hours=1), f1())\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()  # type: Future[None]\n        immediate.set_result(None)\n        yield [f(\"a\", immediate), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"aaaaabbbbb\")\n\n        # With moment, they take turns.\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", gen.moment)]\n        self.assertEqual(\"\".join(calls), \"ababababab\")\n        self.finished = True\n\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"abbbbbaaaa\")\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True\n\n    @skipNotCPython\n    @unittest.skipIf(\n        (3,) < sys.version_info < (3, 6), \"asyncio.Future has reference cycles\"\n    )\n    def test_coroutine_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.coroutine\n        def inner():\n            class Foo(object):\n                pass\n\n            local_var = Foo()\n            self.local_ref = weakref.ref(local_var)\n\n            def dummy():\n                pass\n\n            yield gen.coroutine(dummy)()\n            raise ValueError(\"Some error\")\n\n        @gen.coroutine\n        def inner2():\n            try:\n                yield inner()\n            except ValueError:\n                pass\n\n        self.io_loop.run_sync(inner2, timeout=3)\n\n        self.assertIs(self.local_ref(), None)\n        self.finished = True\n\n    def test_asyncio_future_debug_info(self):\n        self.finished = True\n        # Enable debug mode\n        asyncio_loop = asyncio.get_event_loop()\n        self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug())\n        asyncio_loop.set_debug(True)\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)()\n        self.assertIsInstance(coro, asyncio.Future)\n        # We expect the coroutine repr() to show the place where\n        # it was instantiated\n        expected = \"created at %s:%d\" % (__file__, f.__code__.co_firstlineno + 3)\n        actual = repr(coro)\n        self.assertIn(expected, actual)\n\n    @gen_test\n    def test_asyncio_gather(self):\n        # This demonstrates that tornado coroutines can be understood\n        # by asyncio (This failed prior to Tornado 5.0).\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(1)\n\n        ret = yield asyncio.gather(f(), f())\n        self.assertEqual(ret, [1, 1])\n        self.finished = True\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        # just write, don't finish\n        self.write(\"3\")\n\n\n# \"Undecorated\" here refers to the absence of @asynchronous.\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []  # type: List[str]\n        yield gen.moment\n        self.chunks.append(\"1\")\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append(\"2\")\n        yield gen.moment\n        self.chunks.append(\"3\")\n        yield gen.moment\n        self.write(\"\".join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish(\"ok\")\n\n\nclass NativeCoroutineHandler(RequestHandler):\n    async def get(self):\n        await asyncio.sleep(0)\n        self.write(\"ok\")\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                (\"/coroutine_sequence\", GenCoroutineSequenceHandler),\n                (\n                    \"/coroutine_unfinished_sequence\",\n                    GenCoroutineUnfinishedSequenceHandler,\n                ),\n                (\"/undecorated_coroutine\", UndecoratedCoroutinesHandler),\n                (\"/async_prepare_error\", AsyncPrepareErrorHandler),\n                (\"/native_coroutine\", NativeCoroutineHandler),\n            ]\n        )\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch(\"/coroutine_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch(\"/coroutine_unfinished_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch(\"/undecorated_coroutine\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch(\"/async_prepare_error\")\n        self.assertEqual(response.code, 403)\n\n    def test_native_coroutine_handler(self):\n        response = self.fetch(\"/native_coroutine\")\n        self.assertEqual(response.code, 200)\n        self.assertEqual(response.body, b\"ok\")\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1), lambda: future.set_result(\"asdf\")\n        )\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()),\n        )\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()  # type: Future[str]\n        future.set_result(\"asdf\")\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        # A concurrent future that does not resolve before the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(\n                    self.io_loop.time(), executor.submit(time.sleep, 0.1)\n                )\n\n    @gen_test\n    def test_completed_concurrent_future(self):\n        # A concurrent future that is resolved before we even submit it\n        # to with_timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n\n            def dummy():\n                pass\n\n            f = executor.submit(dummy)\n            f.result()  # wait for completion\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), f)\n\n    @gen_test\n    def test_normal_concurrent_future(self):\n        # A conccurrent future that resolves while waiting for the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(\n                datetime.timedelta(seconds=3600),\n                executor.submit(lambda: time.sleep(0.01)),\n            )\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), \"empty generator iterated\")\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(Future(), bar=Future())\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()  # type: Future[int]\n        f2 = Future()  # type: Future[int]\n        f3 = Future()  # type: Future[int]\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(\n                    dg.current_future == f1 and dr == 24,\n                    \"WaitIterator dict status incorrect\",\n                )\n            elif dg.current_index == \"f2\":\n                self.assertTrue(\n                    dg.current_future == f2 and dr == 42,\n                    \"WaitIterator dict status incorrect\",\n                )\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0], \"exception future invalid\")\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 2, \"wrong index\")\n                elif i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n            i += 1\n\n    @gen_test\n    def test_iterator_async_await(self):\n        # Recreate the previous test with py35 syntax. It's a little clunky\n        # because of the way the previous test handles an exception on\n        # a single iteration.\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n        self.finish_coroutines(0, futures)\n        self.finished = False\n\n        async def f():\n            i = 0\n            g = gen.WaitIterator(*futures)\n            try:\n                async for r in g:\n                    if i == 0:\n                        self.assertEqual(r, 24, \"iterator value incorrect\")\n                        self.assertEqual(g.current_index, 2, \"wrong index\")\n                    else:\n                        raise Exception(\"expected exception on iteration 1\")\n                    i += 1\n            except ZeroDivisionError:\n                i += 1\n            async for r in g:\n                if i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n                else:\n                    raise Exception(\"didn't expect iteration %d\" % i)\n                i += 1\n            self.finished = True\n\n        yield f()\n        self.assertTrue(self.finished)\n\n    @gen_test\n    def test_no_ref(self):\n        # In this usage, there is no direct hard reference to the\n        # WaitIterator itself, only the Future it returns. Since\n        # WaitIterator uses weak references internally to improve GC\n        # performance, this used to cause problems.\n        yield gen.with_timeout(\n            datetime.timedelta(seconds=0.1), gen.WaitIterator(gen.sleep(0)).next()\n        )\n\n\nclass RunnerGCTest(AsyncTestCase):\n    def is_pypy3(self):\n        return platform.python_implementation() == \"PyPy\" and sys.version_info > (3,)\n\n    @gen_test\n    def test_gc(self):\n        # GitHub issue 1769: Runner objects can get GCed unexpectedly\n        # while their future is alive.\n        weakref_scope = [None]  # type: List[Optional[weakref.ReferenceType]]\n\n        def callback():\n            gc.collect(2)\n            weakref_scope[0]().set_result(123)  # type: ignore\n\n        @gen.coroutine\n        def tester():\n            fut = Future()  # type: Future[int]\n            weakref_scope[0] = weakref.ref(fut)\n            self.io_loop.add_callback(callback)\n            yield fut\n\n        yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())\n\n    def test_gc_infinite_coro(self):\n        # GitHub issue 2229: suspended coroutines should be GCed when\n        # their loop is closed, even if they're involved in a reference\n        # cycle.\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def infinite_coro():\n            try:\n                while True:\n                    yield gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        @gen.coroutine\n        def do_something():\n            fut = infinite_coro()\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        loop.close()\n        gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_gc_infinite_async_await(self):\n        # Same as test_gc_infinite_coro, but with a `async def` function\n        import asyncio\n\n        async def infinite_coro(result):\n            try:\n                while True:\n                    await gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def do_something():\n            fut = asyncio.get_event_loop().create_task(infinite_coro(result))\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        with ExpectLog(\"asyncio\", \"Task was destroyed but it is pending\"):\n            loop.close()\n            gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup and one finally\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_multi_moment(self):\n        # Test gen.multi with moment\n        # now that it's not a real Future\n        @gen.coroutine\n        def wait_a_moment():\n            result = yield gen.multi([gen.moment, gen.moment])\n            raise gen.Return(result)\n\n        loop = self.get_new_ioloop()\n        result = loop.run_sync(wait_a_moment)\n        self.assertEqual(result, [None, None])\n\n\nif contextvars is not None:\n    ctx_var = contextvars.ContextVar(\"ctx_var\")  # type: contextvars.ContextVar[int]\n\n\n@unittest.skipIf(contextvars is None, \"contextvars module not present\")\nclass ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n    @gen_test\n    def test_propagate_to_first_yield_with_native_async_function(self):\n        x = 10\n\n        async def native_async_function():\n            self.assertEquals(ctx_var.get(), x)\n\n        ctx_var.set(x)\n        yield native_async_function()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/gen_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "73c33878",
                "new_commit_hash": "2b025386",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/gen_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/gen_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1114,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1114,
                            "length": 16
                        },
                        "section": "class ContextVarsTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # so we must make sure that we maintain that property across yield.",
                                "type": "context"
                            },
                            {
                                "content": "        ctx_var.reset(token)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_propagate_to_first_yield_with_native_async_function(self):",
                                "type": "added"
                            },
                            {
                                "content": "        x = 10",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        async def native_async_function():",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEquals(ctx_var.get(), x)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        ctx_var.set(x)",
                                "type": "added"
                            },
                            {
                                "content": "        yield native_async_function()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "if __name__ == \"__main__\":",
                                "type": "context"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "ContextVarsTest",
                            "content": "class ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n    @gen_test\n    def test_propagate_to_first_yield_with_native_async_function(self):\n        x = 10\n\n        async def native_async_function():\n            self.assertEquals(ctx_var.get(), x)\n\n        ctx_var.set(x)\n        yield native_async_function()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1062,
                            "end_lineno": 1125,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "ContextVarsTest.test_propagate_to_first_yield_with_native_async_function",
                            "content": "class ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n    @gen_test\n    def test_propagate_to_first_yield_with_native_async_function(self):\n        x = 10\n\n        async def native_async_function():\n            self.assertEquals(ctx_var.get(), x)\n\n        ctx_var.set(x)\n        yield native_async_function()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1118,
                            "end_lineno": 1125,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "ContextVarsTest",
                                "content": "class ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n    @gen_test\n    def test_propagate_to_first_yield_with_native_async_function(self):\n        x = 10\n\n        async def native_async_function():\n            self.assertEquals(ctx_var.get(), x)\n\n        ctx_var.set(x)\n        yield native_async_function()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1062,
                                "end_lineno": 1125,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "217d57690eb00a86d9eeaee6fe6280fced683f60^",
    "new_commit_hash": "217d57690eb00a86d9eeaee6fe6280fced683f60",
    "commit_message": "Fix contextvars.Context propagation to first yield with native coroutines (#3176)\n\n* Fix contextvars.Context propagation to first yield with native coroutines",
    "commit_date": "2022-08-26T15:05:22-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "217d57690eb00a86d9eeaee6fe6280fced683f60",
    "test_file_codes": [
        "import asyncio\nfrom concurrent import futures\nimport gc\nimport datetime\nimport platform\nimport sys\nimport time\nimport weakref\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import skipOnTravis, skipNotCPython\nfrom tornado.web import Application, RequestHandler, HTTPError\n\nfrom tornado import gen\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List, Optional  # noqa: F401\n\n\nclass GenBasicTest(AsyncTestCase):\n    @gen.coroutine\n    def delay(self, iterations, arg):\n        \"\"\"Returns arg after a number of IOLoop iterations.\"\"\"\n        for i in range(iterations):\n            yield gen.moment\n        raise gen.Return(arg)\n\n    @gen.coroutine\n    def async_future(self, result):\n        yield gen.moment\n        return result\n\n    @gen.coroutine\n    def async_exception(self, e):\n        yield gen.moment\n        raise e\n\n    @gen.coroutine\n    def add_one_async(self, x):\n        yield gen.moment\n        raise gen.Return(x + 1)\n\n    def test_no_yield(self):\n        @gen.coroutine\n        def f():\n            pass\n\n        self.io_loop.run_sync(f)\n\n    def test_exception_phase1(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_exception_phase2(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield(self):\n        @gen.coroutine\n        def f():\n            yield 42\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.coroutine\n        def f():\n            yield (1, 2)\n\n        self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)\n\n    def test_reuse(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n\n        self.io_loop.run_sync(f)\n        self.io_loop.run_sync(f)\n\n    def test_none(self):\n        @gen.coroutine\n        def f():\n            yield None\n\n        self.io_loop.run_sync(f)\n\n    def test_multi(self):\n        @gen.coroutine\n        def f():\n            results = yield [self.add_one_async(1), self.add_one_async(2)]\n            self.assertEqual(results, [2, 3])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict(self):\n        @gen.coroutine\n        def f():\n            results = yield dict(foo=self.add_one_async(1), bar=self.add_one_async(2))\n            self.assertEqual(results, dict(foo=2, bar=3))\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                [self.delay(3, \"v1\"), self.delay(1, \"v2\")]\n            )\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n\n        self.io_loop.run_sync(f)\n\n    def test_multi_dict_delayed(self):\n        @gen.coroutine\n        def f():\n            # callbacks run at different times\n            responses = yield gen.multi_future(\n                dict(foo=self.delay(3, \"v1\"), bar=self.delay(1, \"v2\"))\n            )\n            self.assertEqual(responses, dict(foo=\"v1\", bar=\"v2\"))\n\n        self.io_loop.run_sync(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.moment for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_multi_empty(self):\n        # Empty lists or dicts should return the same type.\n        x = yield []\n        self.assertTrue(isinstance(x, list))\n        y = yield {}\n        self.assertTrue(isinstance(y, dict))\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    @gen_test\n    def test_multi_future_duplicate(self):\n        # Note that this doesn't work with native corotines, only with\n        # decorated coroutines.\n        f = self.async_future(2)\n        results = yield [self.async_future(1), f, self.async_future(3), f]\n        self.assertEqual(results, [1, 2, 3, 2])\n\n    @gen_test\n    def test_multi_dict_future(self):\n        results = yield dict(foo=self.async_future(1), bar=self.async_future(2))\n        self.assertEqual(results, dict(foo=1, bar=2))\n\n    @gen_test\n    def test_multi_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield gen.Multi(\n                    [\n                        self.async_exception(RuntimeError(\"error 1\")),\n                        self.async_exception(RuntimeError(\"error 2\")),\n                    ]\n                )\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n            )\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.Multi(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    @gen_test\n    def test_multi_future_exceptions(self):\n        with ExpectLog(app_log, \"Multiple exceptions in yield list\"):\n            with self.assertRaises(RuntimeError) as cm:\n                yield [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ]\n        self.assertEqual(str(cm.exception), \"error 1\")\n\n        # With only one exception, no error is logged.\n        with self.assertRaises(RuntimeError):\n            yield [self.async_exception(RuntimeError(\"error 1\")), self.async_future(2)]\n\n        # Exception logging may be explicitly quieted.\n        with self.assertRaises(RuntimeError):\n            yield gen.multi_future(\n                [\n                    self.async_exception(RuntimeError(\"error 1\")),\n                    self.async_exception(RuntimeError(\"error 2\")),\n                ],\n                quiet_exceptions=RuntimeError,\n            )\n\n    def test_sync_raise_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_async_raise_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return()\n\n        self.io_loop.run_sync(f)\n\n    def test_sync_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        self.assertEqual(42, self.io_loop.run_sync(f))\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return((1, 2))\n\n        self.assertEqual((1, 2), self.io_loop.run_sync(f))\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super().setUp()\n\n    def tearDown(self):\n        super().tearDown()\n        assert self.finished\n\n    def test_attributes(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertEqual(coro.__name__, f.__name__)\n        self.assertEqual(coro.__module__, f.__module__)\n        self.assertIs(coro.__wrapped__, f)  # type: ignore\n\n    def test_is_coroutine_function(self):\n        self.finished = True\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)\n        self.assertFalse(gen.is_coroutine_function(f))\n        self.assertTrue(gen.is_coroutine_function(coro))\n        self.assertFalse(gen.is_coroutine_function(coro()))\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n            raise gen.Return(42)\n\n        # This test verifies that an async function can await a\n        # yield-based gen.coroutine, and that a gen.coroutine\n        # (the test method itself) can yield an async function.\n        async def f2():\n            result = await f1()\n            return result\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_asyncio_sleep_zero(self):\n        # asyncio.sleep(0) turns into a special case (equivalent to\n        # `yield None`)\n        async def f():\n            import asyncio\n\n            await asyncio.sleep(0)\n            return 42\n\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_await_mixed_multi_native_future(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n            return 42\n\n        @gen.coroutine\n        def f3():\n            yield gen.moment\n            raise gen.Return(43)\n\n        results = yield [f2(), f3()]\n        self.assertEqual(results, [42, 43])\n        self.finished = True\n\n    @gen_test\n    def test_async_with_timeout(self):\n        async def f1():\n            return 42\n\n        result = yield gen.with_timeout(datetime.timedelta(hours=1), f1())\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            return\n\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_moment(self):\n        calls = []\n\n        @gen.coroutine\n        def f(name, yieldable):\n            for i in range(5):\n                calls.append(name)\n                yield yieldable\n\n        # First, confirm the behavior without moment: each coroutine\n        # monopolizes the event loop until it finishes.\n        immediate = Future()  # type: Future[None]\n        immediate.set_result(None)\n        yield [f(\"a\", immediate), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"aaaaabbbbb\")\n\n        # With moment, they take turns.\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", gen.moment)]\n        self.assertEqual(\"\".join(calls), \"ababababab\")\n        self.finished = True\n\n        calls = []\n        yield [f(\"a\", gen.moment), f(\"b\", immediate)]\n        self.assertEqual(\"\".join(calls), \"abbbbbaaaa\")\n\n    @gen_test\n    def test_sleep(self):\n        yield gen.sleep(0.01)\n        self.finished = True\n\n    @gen_test\n    def test_py3_leak_exception_context(self):\n        class LeakedException(Exception):\n            pass\n\n        @gen.coroutine\n        def inner(iteration):\n            raise LeakedException(iteration)\n\n        try:\n            yield inner(1)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"1\")\n            self.assertIsNone(e.__context__)\n\n        try:\n            yield inner(2)\n        except LeakedException as e:\n            self.assertEqual(str(e), \"2\")\n            self.assertIsNone(e.__context__)\n\n        self.finished = True\n\n    @skipNotCPython\n    @unittest.skipIf(\n        (3,) < sys.version_info < (3, 6), \"asyncio.Future has reference cycles\"\n    )\n    def test_coroutine_refcounting(self):\n        # On CPython, tasks and their arguments should be released immediately\n        # without waiting for garbage collection.\n        @gen.coroutine\n        def inner():\n            class Foo(object):\n                pass\n\n            local_var = Foo()\n            self.local_ref = weakref.ref(local_var)\n\n            def dummy():\n                pass\n\n            yield gen.coroutine(dummy)()\n            raise ValueError(\"Some error\")\n\n        @gen.coroutine\n        def inner2():\n            try:\n                yield inner()\n            except ValueError:\n                pass\n\n        self.io_loop.run_sync(inner2, timeout=3)\n\n        self.assertIs(self.local_ref(), None)\n        self.finished = True\n\n    def test_asyncio_future_debug_info(self):\n        self.finished = True\n        # Enable debug mode\n        asyncio_loop = asyncio.get_event_loop()\n        self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug())\n        asyncio_loop.set_debug(True)\n\n        def f():\n            yield gen.moment\n\n        coro = gen.coroutine(f)()\n        self.assertIsInstance(coro, asyncio.Future)\n        # We expect the coroutine repr() to show the place where\n        # it was instantiated\n        expected = \"created at %s:%d\" % (__file__, f.__code__.co_firstlineno + 3)\n        actual = repr(coro)\n        self.assertIn(expected, actual)\n\n    @gen_test\n    def test_asyncio_gather(self):\n        # This demonstrates that tornado coroutines can be understood\n        # by asyncio (This failed prior to Tornado 5.0).\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(1)\n\n        ret = yield asyncio.gather(f(), f())\n        self.assertEqual(ret, [1, 1])\n        self.finished = True\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @gen.coroutine\n    def get(self):\n        yield gen.moment\n        self.write(\"1\")\n        yield gen.moment\n        self.write(\"2\")\n        yield gen.moment\n        # just write, don't finish\n        self.write(\"3\")\n\n\n# \"Undecorated\" here refers to the absence of @asynchronous.\nclass UndecoratedCoroutinesHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        self.chunks = []  # type: List[str]\n        yield gen.moment\n        self.chunks.append(\"1\")\n\n    @gen.coroutine\n    def get(self):\n        self.chunks.append(\"2\")\n        yield gen.moment\n        self.chunks.append(\"3\")\n        yield gen.moment\n        self.write(\"\".join(self.chunks))\n\n\nclass AsyncPrepareErrorHandler(RequestHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n        raise HTTPError(403)\n\n    def get(self):\n        self.finish(\"ok\")\n\n\nclass NativeCoroutineHandler(RequestHandler):\n    async def get(self):\n        await asyncio.sleep(0)\n        self.write(\"ok\")\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                (\"/coroutine_sequence\", GenCoroutineSequenceHandler),\n                (\n                    \"/coroutine_unfinished_sequence\",\n                    GenCoroutineUnfinishedSequenceHandler,\n                ),\n                (\"/undecorated_coroutine\", UndecoratedCoroutinesHandler),\n                (\"/async_prepare_error\", AsyncPrepareErrorHandler),\n                (\"/native_coroutine\", NativeCoroutineHandler),\n            ]\n        )\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch(\"/coroutine_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch(\"/coroutine_unfinished_sequence\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_undecorated_coroutines(self):\n        response = self.fetch(\"/undecorated_coroutine\")\n        self.assertEqual(response.body, b\"123\")\n\n    def test_async_prepare_error_handler(self):\n        response = self.fetch(\"/async_prepare_error\")\n        self.assertEqual(response.code, 403)\n\n    def test_native_coroutine_handler(self):\n        response = self.fetch(\"/native_coroutine\")\n        self.assertEqual(response.code, 200)\n        self.assertEqual(response.body, b\"ok\")\n\n\nclass WithTimeoutTest(AsyncTestCase):\n    @gen_test\n    def test_timeout(self):\n        with self.assertRaises(gen.TimeoutError):\n            yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future())\n\n    @gen_test\n    def test_completes_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1), lambda: future.set_result(\"asdf\")\n        )\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_fails_before_timeout(self):\n        future = Future()  # type: Future[str]\n        self.io_loop.add_timeout(\n            datetime.timedelta(seconds=0.1),\n            lambda: future.set_exception(ZeroDivisionError()),\n        )\n        with self.assertRaises(ZeroDivisionError):\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n\n    @gen_test\n    def test_already_resolved(self):\n        future = Future()  # type: Future[str]\n        future.set_result(\"asdf\")\n        result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)\n        self.assertEqual(result, \"asdf\")\n\n    @gen_test\n    def test_timeout_concurrent_future(self):\n        # A concurrent future that does not resolve before the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            with self.assertRaises(gen.TimeoutError):\n                yield gen.with_timeout(\n                    self.io_loop.time(), executor.submit(time.sleep, 0.1)\n                )\n\n    @gen_test\n    def test_completed_concurrent_future(self):\n        # A concurrent future that is resolved before we even submit it\n        # to with_timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n\n            def dummy():\n                pass\n\n            f = executor.submit(dummy)\n            f.result()  # wait for completion\n            yield gen.with_timeout(datetime.timedelta(seconds=3600), f)\n\n    @gen_test\n    def test_normal_concurrent_future(self):\n        # A conccurrent future that resolves while waiting for the timeout.\n        with futures.ThreadPoolExecutor(1) as executor:\n            yield gen.with_timeout(\n                datetime.timedelta(seconds=3600),\n                executor.submit(lambda: time.sleep(0.01)),\n            )\n\n\nclass WaitIteratorTest(AsyncTestCase):\n    @gen_test\n    def test_empty_iterator(self):\n        g = gen.WaitIterator()\n        self.assertTrue(g.done(), \"empty generator iterated\")\n\n        with self.assertRaises(ValueError):\n            g = gen.WaitIterator(Future(), bar=Future())\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n    @gen_test\n    def test_already_done(self):\n        f1 = Future()  # type: Future[int]\n        f2 = Future()  # type: Future[int]\n        f3 = Future()  # type: Future[int]\n        f1.set_result(24)\n        f2.set_result(42)\n        f3.set_result(84)\n\n        g = gen.WaitIterator(f1, f2, f3)\n        i = 0\n        while not g.done():\n            r = yield g.next()\n            # Order is not guaranteed, but the current implementation\n            # preserves ordering of already-done Futures.\n            if i == 0:\n                self.assertEqual(g.current_index, 0)\n                self.assertIs(g.current_future, f1)\n                self.assertEqual(r, 24)\n            elif i == 1:\n                self.assertEqual(g.current_index, 1)\n                self.assertIs(g.current_future, f2)\n                self.assertEqual(r, 42)\n            elif i == 2:\n                self.assertEqual(g.current_index, 2)\n                self.assertIs(g.current_future, f3)\n                self.assertEqual(r, 84)\n            i += 1\n\n        self.assertEqual(g.current_index, None, \"bad nil current index\")\n        self.assertEqual(g.current_future, None, \"bad nil current future\")\n\n        dg = gen.WaitIterator(f1=f1, f2=f2)\n\n        while not dg.done():\n            dr = yield dg.next()\n            if dg.current_index == \"f1\":\n                self.assertTrue(\n                    dg.current_future == f1 and dr == 24,\n                    \"WaitIterator dict status incorrect\",\n                )\n            elif dg.current_index == \"f2\":\n                self.assertTrue(\n                    dg.current_future == f2 and dr == 42,\n                    \"WaitIterator dict status incorrect\",\n                )\n            else:\n                self.fail(\"got bad WaitIterator index {}\".format(dg.current_index))\n\n            i += 1\n\n        self.assertEqual(dg.current_index, None, \"bad nil current index\")\n        self.assertEqual(dg.current_future, None, \"bad nil current future\")\n\n    def finish_coroutines(self, iteration, futures):\n        if iteration == 3:\n            futures[2].set_result(24)\n        elif iteration == 5:\n            futures[0].set_exception(ZeroDivisionError())\n        elif iteration == 8:\n            futures[1].set_result(42)\n            futures[3].set_result(84)\n\n        if iteration < 8:\n            self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)\n\n    @gen_test\n    def test_iterator(self):\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n\n        self.finish_coroutines(0, futures)\n\n        g = gen.WaitIterator(*futures)\n\n        i = 0\n        while not g.done():\n            try:\n                r = yield g.next()\n            except ZeroDivisionError:\n                self.assertIs(g.current_future, futures[0], \"exception future invalid\")\n            else:\n                if i == 0:\n                    self.assertEqual(r, 24, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 2, \"wrong index\")\n                elif i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n            i += 1\n\n    @gen_test\n    def test_iterator_async_await(self):\n        # Recreate the previous test with py35 syntax. It's a little clunky\n        # because of the way the previous test handles an exception on\n        # a single iteration.\n        futures = [Future(), Future(), Future(), Future()]  # type: List[Future[int]]\n        self.finish_coroutines(0, futures)\n        self.finished = False\n\n        async def f():\n            i = 0\n            g = gen.WaitIterator(*futures)\n            try:\n                async for r in g:\n                    if i == 0:\n                        self.assertEqual(r, 24, \"iterator value incorrect\")\n                        self.assertEqual(g.current_index, 2, \"wrong index\")\n                    else:\n                        raise Exception(\"expected exception on iteration 1\")\n                    i += 1\n            except ZeroDivisionError:\n                i += 1\n            async for r in g:\n                if i == 2:\n                    self.assertEqual(r, 42, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 1, \"wrong index\")\n                elif i == 3:\n                    self.assertEqual(r, 84, \"iterator value incorrect\")\n                    self.assertEqual(g.current_index, 3, \"wrong index\")\n                else:\n                    raise Exception(\"didn't expect iteration %d\" % i)\n                i += 1\n            self.finished = True\n\n        yield f()\n        self.assertTrue(self.finished)\n\n    @gen_test\n    def test_no_ref(self):\n        # In this usage, there is no direct hard reference to the\n        # WaitIterator itself, only the Future it returns. Since\n        # WaitIterator uses weak references internally to improve GC\n        # performance, this used to cause problems.\n        yield gen.with_timeout(\n            datetime.timedelta(seconds=0.1), gen.WaitIterator(gen.sleep(0)).next()\n        )\n\n\nclass RunnerGCTest(AsyncTestCase):\n    def is_pypy3(self):\n        return platform.python_implementation() == \"PyPy\" and sys.version_info > (3,)\n\n    @gen_test\n    def test_gc(self):\n        # GitHub issue 1769: Runner objects can get GCed unexpectedly\n        # while their future is alive.\n        weakref_scope = [None]  # type: List[Optional[weakref.ReferenceType]]\n\n        def callback():\n            gc.collect(2)\n            weakref_scope[0]().set_result(123)  # type: ignore\n\n        @gen.coroutine\n        def tester():\n            fut = Future()  # type: Future[int]\n            weakref_scope[0] = weakref.ref(fut)\n            self.io_loop.add_callback(callback)\n            yield fut\n\n        yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())\n\n    def test_gc_infinite_coro(self):\n        # GitHub issue 2229: suspended coroutines should be GCed when\n        # their loop is closed, even if they're involved in a reference\n        # cycle.\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def infinite_coro():\n            try:\n                while True:\n                    yield gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        @gen.coroutine\n        def do_something():\n            fut = infinite_coro()\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        loop.close()\n        gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_gc_infinite_async_await(self):\n        # Same as test_gc_infinite_coro, but with a `async def` function\n        import asyncio\n\n        async def infinite_coro(result):\n            try:\n                while True:\n                    await gen.sleep(1e-3)\n                    result.append(True)\n            finally:\n                # coroutine finalizer\n                result.append(None)\n\n        loop = self.get_new_ioloop()\n        result = []  # type: List[Optional[bool]]\n        wfut = []\n\n        @gen.coroutine\n        def do_something():\n            fut = asyncio.get_event_loop().create_task(infinite_coro(result))\n            fut._refcycle = fut  # type: ignore\n            wfut.append(weakref.ref(fut))\n            yield gen.sleep(0.2)\n\n        loop.run_sync(do_something)\n        with ExpectLog(\"asyncio\", \"Task was destroyed but it is pending\"):\n            loop.close()\n            gc.collect()\n        # Future was collected\n        self.assertIs(wfut[0](), None)\n        # At least one wakeup and one finally\n        self.assertGreaterEqual(len(result), 2)\n        if not self.is_pypy3():\n            # coroutine finalizer was called (not on PyPy3 apparently)\n            self.assertIs(result[-1], None)\n\n    def test_multi_moment(self):\n        # Test gen.multi with moment\n        # now that it's not a real Future\n        @gen.coroutine\n        def wait_a_moment():\n            result = yield gen.multi([gen.moment, gen.moment])\n            raise gen.Return(result)\n\n        loop = self.get_new_ioloop()\n        result = loop.run_sync(wait_a_moment)\n        self.assertEqual(result, [None, None])\n\n\nif contextvars is not None:\n    ctx_var = contextvars.ContextVar(\"ctx_var\")  # type: contextvars.ContextVar[int]\n\n\n@unittest.skipIf(contextvars is None, \"contextvars module not present\")\nclass ContextVarsTest(AsyncTestCase):\n    async def native_root(self, x):\n        ctx_var.set(x)\n        await self.inner(x)\n\n    @gen.coroutine\n    def gen_root(self, x):\n        ctx_var.set(x)\n        yield\n        yield self.inner(x)\n\n    async def inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        await self.gen_inner(x)\n        self.assertEqual(ctx_var.get(), x)\n\n        # IOLoop.run_in_executor doesn't automatically copy context\n        ctx = contextvars.copy_context()\n        await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))\n        self.assertEqual(ctx_var.get(), x)\n\n        # Neither does asyncio's run_in_executor.\n        await asyncio.get_event_loop().run_in_executor(\n            None, lambda: ctx.run(self.thread_inner, x)\n        )\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen.coroutine\n    def gen_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n        yield\n        self.assertEqual(ctx_var.get(), x)\n\n    def thread_inner(self, x):\n        self.assertEqual(ctx_var.get(), x)\n\n    @gen_test\n    def test_propagate(self):\n        # Verify that context vars get propagated across various\n        # combinations of native and decorated coroutines.\n        yield [\n            self.native_root(1),\n            self.native_root(2),\n            self.gen_root(3),\n            self.gen_root(4),\n        ]\n\n    @gen_test\n    def test_reset(self):\n        token = ctx_var.set(1)\n        yield\n        # reset asserts that we are still at the same level of the context tree,\n        # so we must make sure that we maintain that property across yield.\n        ctx_var.reset(token)\n\n    @gen_test\n    def test_propagate_to_first_yield_with_native_async_function(self):\n        x = 10\n\n        async def native_async_function():\n            self.assertEquals(ctx_var.get(), x)\n\n        ctx_var.set(x)\n        yield native_async_function()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 927ms\nPrepared 1 package in 1.24s\nInstalled 1 package in 1ms\n + tornado==6.3.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60)\nResolved 29 packages in 16ms\nInstalled 29 packages in 180ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60\n........................................................................\ncollected 72 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ContextVarsTest::test_propagate\nPASSED r2e_tests.test_1::ContextVarsTest::test_propagate_to_first_yield_with_native_async_function\nPASSED r2e_tests.test_1::ContextVarsTest::test_reset\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenBasicTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenBasicTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenBasicTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenBasicTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenBasicTest::test_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict_delayed\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_empty\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_exceptions\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future_duplicate\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future_exceptions\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_performance\nPASSED r2e_tests.test_1::GenBasicTest::test_no_yield\nPASSED r2e_tests.test_1::GenBasicTest::test_none\nPASSED r2e_tests.test_1::GenBasicTest::test_reuse\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_await\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_await_mixed_multi_native_future\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_with_timeout\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_future_debug_info\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_gather\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_sleep_zero\nPASSED r2e_tests.test_1::GenCoroutineTest::test_attributes\nPASSED r2e_tests.test_1::GenCoroutineTest::test_coroutine_refcounting\nPASSED r2e_tests.test_1::GenCoroutineTest::test_is_coroutine_function\nPASSED r2e_tests.test_1::GenCoroutineTest::test_moment\nPASSED r2e_tests.test_1::GenCoroutineTest::test_py3_leak_exception_context\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sleep\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenWebTest::test_async_prepare_error_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_native_coroutine_handler\nPASSED r2e_tests.test_1::GenWebTest::test_undecorated_coroutines\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc_infinite_async_await\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc_infinite_coro\nPASSED r2e_tests.test_1::RunnerGCTest::test_multi_moment\nPASSED r2e_tests.test_1::WaitIteratorTest::test_already_done\nPASSED r2e_tests.test_1::WaitIteratorTest::test_empty_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator_async_await\nPASSED r2e_tests.test_1::WaitIteratorTest::test_no_ref\nPASSED r2e_tests.test_1::WithTimeoutTest::test_already_resolved\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completed_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completes_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_fails_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_normal_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout_concurrent_future\n=================== 72 passed in 0.92s ===================\n",
    "new_commit_res_stderr": "403 GET /async_prepare_error (127.0.0.1) 0.57ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60\n........................................................................\ncollected 72 items\n\n=================================== ERRORS =====================================\n__________ ContextVarsTest.test_propagate_to_first_yield_with_native_async_function __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/tornado/testing.py\", line 102, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/tornado/testing.py\", line 662, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/tornado/ioloop.py\", line 529, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/tornado/gen.py\", line 776, in run\n    yielded = self.gen.throw(*exc_info)  # type: ignore\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/r2e_tests/test_1.py\", line 1125, in test_propagate_to_first_yield_with_native_async_function\n    yield native_async_function()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/tornado/gen.py\", line 769, in run\n    value = future.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_217d57690eb00a86d9eeaee6fe6280fced683f60/r2e_tests/test_1.py\", line 1122, in native_async_function\n    self.assertEquals(ctx_var.get(), x)\nLookupError: <ContextVar name='ctx_var' at 0x7a51a43a9310>\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ContextVarsTest::test_propagate\nERROR r2e_tests.test_1::ContextVarsTest::test_propagate_to_first_yield_with_native_async_function\nPASSED r2e_tests.test_1::ContextVarsTest::test_reset\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenBasicTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenBasicTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenBasicTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenBasicTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenBasicTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenBasicTest::test_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict_delayed\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_dict_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_empty\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_exceptions\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future_duplicate\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_future_exceptions\nPASSED r2e_tests.test_1::GenBasicTest::test_multi_performance\nPASSED r2e_tests.test_1::GenBasicTest::test_no_yield\nPASSED r2e_tests.test_1::GenBasicTest::test_none\nPASSED r2e_tests.test_1::GenBasicTest::test_reuse\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenBasicTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_await\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_await_mixed_multi_native_future\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_with_timeout\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_future_debug_info\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_gather\nPASSED r2e_tests.test_1::GenCoroutineTest::test_asyncio_sleep_zero\nPASSED r2e_tests.test_1::GenCoroutineTest::test_attributes\nPASSED r2e_tests.test_1::GenCoroutineTest::test_coroutine_refcounting\nPASSED r2e_tests.test_1::GenCoroutineTest::test_is_coroutine_function\nPASSED r2e_tests.test_1::GenCoroutineTest::test_moment\nPASSED r2e_tests.test_1::GenCoroutineTest::test_py3_leak_exception_context\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sleep\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenWebTest::test_async_prepare_error_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_native_coroutine_handler\nPASSED r2e_tests.test_1::GenWebTest::test_undecorated_coroutines\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc_infinite_async_await\nPASSED r2e_tests.test_1::RunnerGCTest::test_gc_infinite_coro\nPASSED r2e_tests.test_1::RunnerGCTest::test_multi_moment\nPASSED r2e_tests.test_1::WaitIteratorTest::test_already_done\nPASSED r2e_tests.test_1::WaitIteratorTest::test_empty_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator\nPASSED r2e_tests.test_1::WaitIteratorTest::test_iterator_async_await\nPASSED r2e_tests.test_1::WaitIteratorTest::test_no_ref\nPASSED r2e_tests.test_1::WithTimeoutTest::test_already_resolved\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completed_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_completes_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_fails_before_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_normal_concurrent_future\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout\nPASSED r2e_tests.test_1::WithTimeoutTest::test_timeout_concurrent_future\n=================== 1 error, 71 passed in 0.88s ===================\n",
    "old_commit_res_stderr": "403 GET /async_prepare_error (127.0.0.1) 1.38ms\n"
}
tornado/gen.py tornado/test/gen_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** ContextVars Context Not Propagated to First Yield in Native Coroutines

**Description:**
When using native `async` functions with coroutines, the `contextvars.Context` is not correctly propagated to the first yield point. This results in a `LookupError` when attempting to access context variables within the coroutine after the first yield.

**Example Code:**
```python
import contextvars
import asyncio

ctx_var = contextvars.ContextVar('ctx_var')

async def native_async_function():
    print(ctx_var.get())

def run_coroutine():
    ctx_var.set(10)
    asyncio.run(native_async_function())

run_coroutine()
```
**Expected Behavior:**
The context variable `ctx_var` should retain its value (`10`) within the `native_async_function` after yielding, allowing it to be accessed without errors.

**Actual Behavior:**
A `LookupError` is raised when `ctx_var.get()` is called inside `native_async_function`, indicating that the context variable is not available in the coroutine's context after the first yield.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` implements generator-based coroutines.

.. note::

   The "decorator and generator" approach in this module is a
   precursor to native coroutines (using ``async def`` and ``await``)
   which were introduced in Python 3.5. Applications that do not
   require compatibility with older versions of Python should use
   native coroutines instead. Some parts of this module are still
   useful with native coroutines, notably `multi`, `sleep`,
   `WaitIterator`, and `with_timeout`. Some of these functions have
   counterparts in the `asyncio` module which may be used as well,
   although the two may not necessarily be 100% compatible.

Coroutines provide an easier way to work in an asynchronous
environment than chaining callbacks. Code using coroutines is
technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, here's a coroutine-based handler:

.. testcode::

    class GenAsyncHandler(RequestHandler):
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            response = yield http_client.fetch("http://example.com")
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

Asynchronous functions in Tornado return an ``Awaitable`` or `.Future`;
yielding this object returns its result.

You can also yield a list or dict of other yieldable objects, which
will be started at the same time and run in parallel; a list or dict
of results will be returned when they are all finished:

.. testcode::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]
        response_dict = yield dict(response3=http_client.fetch(url3),
                                   response4=http_client.fetch(url4))
        response3 = response_dict['response3']
        response4 = response_dict['response4']

.. testoutput::
   :hide:

If ``tornado.platform.twisted`` is imported, it is also possible to
yield Twisted's ``Deferred`` objects. See the `convert_yielded`
function to extend this mechanism.

.. versionchanged:: 3.2
   Dict support added.

.. versionchanged:: 4.1
   Support added for yielding ``asyncio`` Futures and Twisted Deferreds
   via ``singledispatch``.

"""
import asyncio
import builtins
import collections
from collections.abc import Generator
import concurrent.futures
import datetime
import functools
from functools import singledispatch
from inspect import isawaitable
import sys
import types

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
    future_set_result_unless_cancelled,
)
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado.util import TimeoutError

try:
    import contextvars
except ImportError:
    contextvars = None  # type: ignore

import typing
from typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload

if typing.TYPE_CHECKING:
    from typing import Sequence, Deque, Optional, Set, Iterable  # noqa: F401

_T = typing.TypeVar("_T")

_Yieldable = Union[
    None, Awaitable, List[Awaitable], Dict[Any, Awaitable], concurrent.futures.Future
]


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


def _value_from_stopiteration(e: Union[StopIteration, "Return"]) -> Any:
    try:
        # StopIteration has a value attribute beginning in py33.
        # So does our Return class.
        return e.value
    except AttributeError:
        pass
    try:
        # Cython backports coroutine functionality by putting the value in
        # e.args[0].
        return e.args[0]
    except (AttributeError, IndexError):
        return None


def _create_future() -> Future:
    future = Future()  # type: Future
    # Fixup asyncio debug info by removing extraneous stack entries
    source_traceback = getattr(future, "_source_traceback", ())
    while source_traceback:
        # Each traceback entry is equivalent to a
        # (filename, self.lineno, self.name, self.line) tuple
        filename = source_traceback[-1][0]
        if filename == __file__:
            del source_traceback[-1]
        else:
            break
    return future


def _fake_ctx_run(f: Callable[..., _T], *args: Any, **kw: Any) -> _T:
    return f(*args, **kw)


@overload
def coroutine(
    func: Callable[..., "Generator[Any, Any, _T]"]
) -> Callable[..., "Future[_T]"]:
    ...


@overload
def coroutine(func: Callable[..., _T]) -> Callable[..., "Future[_T]"]:
    ...


def coroutine(
    func: Union[Callable[..., "Generator[Any, Any, _T]"], Callable[..., _T]]
) -> Callable[..., "Future[_T]"]:
    """Decorator for asynchronous generators.

    For compatibility with older versions of Python, coroutines may
    also "return" by raising the special exception `Return(value)
    <Return>`.

    Functions with this decorator return a `.Future`.

    .. warning::

       When exceptions occur inside a coroutine, the exception
       information will be stored in the `.Future` object. You must
       examine the result of the `.Future` object, or the exception
       may go unnoticed by your code. This means yielding the function
       if called from another coroutine, using something like
       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`
       to `.IOLoop.add_future`.

    .. versionchanged:: 6.0

       The ``callback`` argument was removed. Use the returned
       awaitable object instead.

    """

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # type: (*Any, **Any) -> Future[_T]
        # This function is type-annotated with a comment to work around
        # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in
        future = _create_future()
        if contextvars is not None:
            ctx_run = contextvars.copy_context().run  # type: Callable
        else:
            ctx_run = _fake_ctx_run
        try:
            result = ctx_run(func, *args, **kwargs)
        except (Return, StopIteration) as e:
            result = _value_from_stopiteration(e)
        except Exception:
            future_set_exc_info(future, sys.exc_info())
            try:
                return future
            finally:
                # Avoid circular references
                future = None  # type: ignore
        else:
            if isinstance(result, Generator):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    yielded = ctx_run(next, result)
                except (StopIteration, Return) as e:
                    future_set_result_unless_cancelled(
                        future, _value_from_stopiteration(e)
                    )
                except Exception:
                    future_set_exc_info(future, sys.exc_info())
                else:
                    # Provide strong references to Runner objects as long
                    # as their result future objects also have strong
                    # references (typically from the parent coroutine's
                    # Runner). This keeps the coroutine's Runner alive.
                    # We do this by exploiting the public API
                    # add_done_callback() instead of putting a private
                    # attribute on the Future.
                    # (GitHub issues #1769, #2229).
                    runner = Runner(ctx_run, result, future, yielded)
                    future.add_done_callback(lambda _: runner)
                yielded = None
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None  # type: ignore
        future_set_result_unless_cancelled(future, result)
        return future

    wrapper.__wrapped__ = func  # type: ignore
    wrapper.__tornado_coroutine__ = True  # type: ignore
    return wrapper


def is_coroutine_function(func: Any) -> bool:
    """Return whether *func* is a coroutine function, i.e. a function
    wrapped with `~.gen.coroutine`.

    .. versionadded:: 4.5
    """
    return getattr(func, "__tornado_coroutine__", False)


class Return(Exception):
    """Special exception to return a value from a `coroutine`.

    If this exception is raised, its value argument is used as the
    result of the coroutine::

        @gen.coroutine
        def fetch_json(url):
            response = yield AsyncHTTPClient().fetch(url)
            raise gen.Return(json_decode(response.body))

    In Python 3.3, this exception is no longer necessary: the ``return``
    statement can be used directly to return a value (previously
    ``yield`` and ``return`` with a value could not be combined in the
    same function).

    By analogy with the return statement, the value argument is optional,
    but it is never necessary to ``raise gen.Return()``.  The ``return``
    statement can be used with no arguments instead.
    """

    def __init__(self, value: Any = None) -> None:
        super().__init__()
        self.value = value
        # Cython recognizes subclasses of StopIteration with a .args tuple.
        self.args = (value,)


class WaitIterator(object):
    """Provides an iterator to yield the results of awaitables as they finish.

    Yielding a set of awaitables like this:

    ``results = yield [awaitable1, awaitable2]``

    pauses the coroutine until both ``awaitable1`` and ``awaitable2``
    return, and then restarts the coroutine with the results of both
    awaitables. If either awaitable raises an exception, the
    expression will raise that exception and all the results will be
    lost.

    If you need to get the result of each awaitable as soon as possible,
    or if you need the result of some awaitables even if others produce
    errors, you can use ``WaitIterator``::

      wait_iterator = gen.WaitIterator(awaitable1, awaitable2)
      while not wait_iterator.done():
          try:
              result = yield wait_iterator.next()
          except Exception as e:
              print("Error {} from {}".format(e, wait_iterator.current_future))
          else:
              print("Result {} received from {} at {}".format(
                  result, wait_iterator.current_future,
                  wait_iterator.current_index))

    Because results are returned as soon as they are available the
    output from the iterator *will not be in the same order as the
    input arguments*. If you need to know which future produced the
    current result, you can use the attributes
    ``WaitIterator.current_future``, or ``WaitIterator.current_index``
    to get the index of the awaitable from the input list. (if keyword
    arguments were used in the construction of the `WaitIterator`,
    ``current_index`` will use the corresponding keyword).

    On Python 3.5, `WaitIterator` implements the async iterator
    protocol, so it can be used with the ``async for`` statement (note
    that in this version the entire iteration is aborted if any value
    raises an exception, while the previous example can continue past
    individual errors)::

      async for result in gen.WaitIterator(future1, future2):
          print("Result {} received from {} at {}".format(
              result, wait_iterator.current_future,
              wait_iterator.current_index))

    .. versionadded:: 4.1

    .. versionchanged:: 4.3
       Added ``async for`` support in Python 3.5.

    """

    _unfinished = {}  # type: Dict[Future, Union[int, str]]

    def __init__(self, *args: Future, **kwargs: Future) -> None:
        if args and kwargs:
            raise ValueError("You must provide args or kwargs, not both")

        if kwargs:
            self._unfinished = dict((f, k) for (k, f) in kwargs.items())
            futures = list(kwargs.values())  # type: Sequence[Future]
        else:
            self._unfinished = dict((f, i) for (i, f) in enumerate(args))
            futures = args

        self._finished = collections.deque()  # type: Deque[Future]
        self.current_index = None  # type: Optional[Union[str, int]]
        self.current_future = None  # type: Optional[Future]
        self._running_future = None  # type: Optional[Future]

        for future in futures:
            future_add_done_callback(future, self._done_callback)

    def done(self) -> bool:
        """Returns True if this iterator has no more results."""
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True

    def next(self) -> Future:
        """Returns a `.Future` that will yield the next available result.

        Note that this `.Future` will not be the same object as any of
        the inputs.
        """
        self._running_future = Future()

        if self._finished:
            return self._return_result(self._finished.popleft())

        return self._running_future

    def _done_callback(self, done: Future) -> None:
        if self._running_future and not self._running_future.done():
            self._return_result(done)
        else:
            self._finished.append(done)

    def _return_result(self, done: Future) -> Future:
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        if self._running_future is None:
            raise Exception("no future is running")
        chain_future(done, self._running_future)

        res = self._running_future
        self._running_future = None
        self.current_future = done
        self.current_index = self._unfinished.pop(done)

        return res

    def __aiter__(self) -> typing.AsyncIterator:
        return self

    def __anext__(self) -> Future:
        if self.done():
            # Lookup by name to silence pyflakes on older versions.
            raise getattr(builtins, "StopAsyncIteration")()
        return self.next()


def multi(
    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
    """Runs multiple asynchronous operations in parallel.

    ``children`` may either be a list or a dict whose values are
    yieldable objects. ``multi()`` returns a new yieldable
    object that resolves to a parallel structure containing their
    results. If ``children`` is a list, the result is a list of
    results in the same order; if it is a dict, the result is a dict
    with the same keys.

    That is, ``results = yield multi(list_of_futures)`` is equivalent
    to::

        results = []
        for future in list_of_futures:
            results.append(yield future)

    If any children raise exceptions, ``multi()`` will raise the first
    one. All others will be logged, unless they are of types
    contained in the ``quiet_exceptions`` argument.

    In a ``yield``-based coroutine, it is not normally necessary to
    call this function directly, since the coroutine runner will
    do it automatically when a list or dict is yielded. However,
    it is necessary in ``await``-based coroutines, or to pass
    the ``quiet_exceptions`` argument.

    This function is available under the names ``multi()`` and ``Multi()``
    for historical reasons.

    Cancelling a `.Future` returned by ``multi()`` does not cancel its
    children. `asyncio.gather` is similar to ``multi()``, but it does
    cancel its children.

    .. versionchanged:: 4.2
       If multiple yieldables fail, any exceptions after the first
       (which is raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. versionchanged:: 4.3
       Replaced the class ``Multi`` and the function ``multi_future``
       with a unified function ``multi``. Added support for yieldables
       other than ``YieldPoint`` and `.Future`.

    """
    return multi_future(children, quiet_exceptions=quiet_exceptions)


Multi = multi


def multi_future(
    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
    """Wait for multiple asynchronous futures in parallel.

    Since Tornado 6.0, this function is exactly the same as `multi`.

    .. versionadded:: 4.0

    .. versionchanged:: 4.2
       If multiple ``Futures`` fail, any exceptions after the first (which is
       raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. deprecated:: 4.3
       Use `multi` instead.
    """
    if isinstance(children, dict):
        keys = list(children.keys())  # type: Optional[List]
        children_seq = children.values()  # type: Iterable
    else:
        keys = None
        children_seq = children
    children_futs = list(map(convert_yielded, children_seq))
    assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs)
    unfinished_children = set(children_futs)

    future = _create_future()
    if not children_futs:
        future_set_result_unless_cancelled(future, {} if keys is not None else [])

    def callback(fut: Future) -> None:
        unfinished_children.remove(fut)
        if not unfinished_children:
            result_list = []
            for f in children_futs:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            app_log.error(
                                "Multiple exceptions in yield list", exc_info=True
                            )
                    else:
                        future_set_exc_info(future, sys.exc_info())
            if not future.done():
                if keys is not None:
                    future_set_result_unless_cancelled(
                        future, dict(zip(keys, result_list))
                    )
                else:
                    future_set_result_unless_cancelled(future, result_list)

    listening = set()  # type: Set[Future]
    for f in children_futs:
        if f not in listening:
            listening.add(f)
            future_add_done_callback(f, callback)
    return future


def maybe_future(x: Any) -> Future:
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.

    .. deprecated:: 4.3
       This function only handles ``Futures``, not other yieldable objects.
       Instead of `maybe_future`, check for the non-future result types
       you expect (often just ``None``), and ``yield`` anything unknown.
    """
    if is_future(x):
        return x
    else:
        fut = _create_future()
        fut.set_result(x)
        return fut


def with_timeout(
    timeout: Union[float, datetime.timedelta],
    future: _Yieldable,
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> Future:
    """Wraps a `.Future` (or other yieldable object) in a timeout.

    Raises `tornado.util.TimeoutError` if the input future does not
    complete before ``timeout``, which may be specified in any form
    allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
    an absolute time relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is either of a type contained in
    ``quiet_exceptions`` (which may be an exception type or a sequence of
    types), or an ``asyncio.CancelledError``.

    The wrapped `.Future` is not canceled when the timeout expires,
    permitting it to be reused. `asyncio.wait_for` is similar to this
    function but it does cancel the wrapped `.Future` on timeout.

    .. versionadded:: 4.0

    .. versionchanged:: 4.1
       Added the ``quiet_exceptions`` argument and the logging of unhandled
       exceptions.

    .. versionchanged:: 4.4
       Added support for yieldable objects other than `.Future`.

    .. versionchanged:: 6.0.3
       ``asyncio.CancelledError`` is now always considered "quiet".

    .. versionchanged:: 6.2
       ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.

    """
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    future_converted = convert_yielded(future)
    result = _create_future()
    chain_future(future_converted, result)
    io_loop = IOLoop.current()

    def error_callback(future: Future) -> None:
        try:
            future.result()
        except asyncio.CancelledError:
            pass
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                app_log.error(
                    "Exception in Future %r after timeout", future, exc_info=True
                )

    def timeout_callback() -> None:
        if not result.done():
            result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future_add_done_callback(future_converted, error_callback)

    timeout_handle = io_loop.add_timeout(timeout, timeout_callback)
    if isinstance(future_converted, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future_add_done_callback(
            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)
        )
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(
            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)
        )
    return result


def sleep(duration: float) -> "Future[None]":
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).

    .. versionadded:: 4.1
    """
    f = _create_future()
    IOLoop.current().call_later(
        duration, lambda: future_set_result_unless_cancelled(f, None)
    )
    return f


class _NullFuture(object):
    """_NullFuture resembles a Future that finished with a result of None.

    It's not actually a `Future` to avoid depending on a particular event loop.
    Handled as a special case in the coroutine runner.

    We lie and tell the type checker that a _NullFuture is a Future so
    we don't have to leak _NullFuture into lots of public APIs. But
    this means that the type checker can't warn us when we're passing
    a _NullFuture into a code path that doesn't understand what to do
    with it.
    """

    def result(self) -> None:
        return None

    def done(self) -> bool:
        return True


# _null_future is used as a dummy value in the coroutine runner. It differs
# from moment in that moment always adds a delay of one IOLoop iteration
# while _null_future is processed as soon as possible.
_null_future = typing.cast(Future, _NullFuture())

moment = typing.cast(Future, _NullFuture())
moment.__doc__ = """A special object which may be yielded to allow the IOLoop to run for
one iteration.

This is not needed in normal use but it can be helpful in long-running
coroutines that are likely to yield Futures that are ready instantly.

Usage: ``yield gen.moment``

In native coroutines, the equivalent of ``yield gen.moment`` is
``await asyncio.sleep(0)``.

.. versionadded:: 4.0

.. deprecated:: 4.5
   ``yield None`` (or ``yield`` with no argument) is now equivalent to
    ``yield gen.moment``.
"""


class Runner(object):
    """Internal implementation of `tornado.gen.coroutine`.

    Maintains information about pending callbacks and their results.

    The results of the generator are stored in ``result_future`` (a
    `.Future`)
    """

    def __init__(
        self,
        ctx_run: Callable,
        gen: "Generator[_Yieldable, Any, _T]",
        result_future: "Future[_T]",
        first_yielded: _Yieldable,
    ) -> None:
        self.ctx_run = ctx_run
        self.gen = gen
        self.result_future = result_future
        self.future = _null_future  # type: Union[None, Future]
        self.running = False
        self.finished = False
        self.io_loop = IOLoop.current()
        if self.handle_yield(first_yielded):
            gen = result_future = first_yielded = None  # type: ignore
            self.ctx_run(self.run)

    def run(self) -> None:
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if future is None:
                    raise Exception("No pending future")
                if not future.done():
                    return
                self.future = None
                try:
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        exc_info = sys.exc_info()
                    future = None

                    if exc_info is not None:
                        try:
                            yielded = self.gen.throw(*exc_info)  # type: ignore
                        finally:
                            # Break up a reference to itself
                            # for faster GC on CPython.
                            exc_info = None
                    else:
                        yielded = self.gen.send(value)

                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    future_set_result_unless_cancelled(
                        self.result_future, _value_from_stopiteration(e)
                    )
                    self.result_future = None  # type: ignore
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    future_set_exc_info(self.result_future, sys.exc_info())
                    self.result_future = None  # type: ignore
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False

    def handle_yield(self, yielded: _Yieldable) -> bool:
        try:
            self.future = convert_yielded(yielded)
        except BadYieldError:
            self.future = Future()
            future_set_exc_info(self.future, sys.exc_info())

        if self.future is moment:
            self.io_loop.add_callback(self.ctx_run, self.run)
            return False
        elif self.future is None:
            raise Exception("no pending future")
        elif not self.future.done():

            def inner(f: Any) -> None:
                # Break a reference cycle to speed GC.
                f = None  # noqa: F841
                self.ctx_run(self.run)

            self.io_loop.add_future(self.future, inner)
            return False
        return True

    def handle_exception(
        self, typ: Type[Exception], value: Exception, tb: types.TracebackType
    ) -> bool:
        if not self.running and not self.finished:
            self.future = Future()
            future_set_exc_info(self.future, (typ, value, tb))
            self.ctx_run(self.run)
            return True
        else:
            return False


# Convert Awaitables into Futures.
try:
    _wrap_awaitable = asyncio.ensure_future
except AttributeError:
    # asyncio.ensure_future was introduced in Python 3.4.4, but
    # Debian jessie still ships with 3.4.2 so try the old name.
    _wrap_awaitable = getattr(asyncio, "async")


def convert_yielded(yielded: _Yieldable) -> Future:
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and
    Futures. This has the side effect of starting any coroutines that
    did not start themselves, similar to `asyncio.ensure_future`.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1

    """
    if yielded is None or yielded is moment:
        return moment
    elif yielded is _null_future:
        return _null_future
    elif isinstance(yielded, (list, dict)):
        return multi(yielded)  # type: ignore
    elif is_future(yielded):
        return typing.cast(Future, yielded)
    elif isawaitable(yielded):
        return _wrap_awaitable(yielded)  # type: ignore
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,))


convert_yielded = singledispatch(convert_yielded)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** ContextVars Context Not Propagated to First Yield in Native Coroutines

**Description:**
When using native `async` functions with coroutines, the `contextvars.Context` is not correctly propagated to the first yield point. This results in a `LookupError` when attempting to access context variables within the coroutine after the first yield.

**Example Code:**
```python
import contextvars
import asyncio

ctx_var = contextvars.ContextVar('ctx_var')

async def native_async_function():
    print(ctx_var.get())

def run_coroutine():
    ctx_var.set(10)
    asyncio.run(native_async_function())

run_coroutine()
```
**Expected Behavior:**
The context variable `ctx_var` should retain its value (`10`) within the `native_async_function` after yielding, allowing it to be accessed without errors.

**Actual Behavior:**
A `LookupError` is raised when `ctx_var.get()` is called inside `native_async_function`, indicating that the context variable is not available in the coroutine's context after the first yield.

[/ISSUE]
{
    "ContextVarsTest.test_propagate": "PASSED",
    "ContextVarsTest.test_propagate_to_first_yield_with_native_async_function": "PASSED",
    "ContextVarsTest.test_reset": "PASSED",
    "GenBasicTest.test_async_raise_return": "PASSED",
    "GenBasicTest.test_async_raise_return_value": "PASSED",
    "GenBasicTest.test_async_raise_return_value_tuple": "PASSED",
    "GenBasicTest.test_bogus_yield": "PASSED",
    "GenBasicTest.test_bogus_yield_tuple": "PASSED",
    "GenBasicTest.test_exception_phase1": "PASSED",
    "GenBasicTest.test_exception_phase2": "PASSED",
    "GenBasicTest.test_future": "PASSED",
    "GenBasicTest.test_multi": "PASSED",
    "GenBasicTest.test_multi_delayed": "PASSED",
    "GenBasicTest.test_multi_dict": "PASSED",
    "GenBasicTest.test_multi_dict_delayed": "PASSED",
    "GenBasicTest.test_multi_dict_future": "PASSED",
    "GenBasicTest.test_multi_empty": "PASSED",
    "GenBasicTest.test_multi_exceptions": "PASSED",
    "GenBasicTest.test_multi_future": "PASSED",
    "GenBasicTest.test_multi_future_duplicate": "PASSED",
    "GenBasicTest.test_multi_future_exceptions": "PASSED",
    "GenBasicTest.test_multi_performance": "PASSED",
    "GenBasicTest.test_no_yield": "PASSED",
    "GenBasicTest.test_none": "PASSED",
    "GenBasicTest.test_reuse": "PASSED",
    "GenBasicTest.test_sync_raise_return": "PASSED",
    "GenBasicTest.test_sync_raise_return_value": "PASSED",
    "GenBasicTest.test_sync_raise_return_value_tuple": "PASSED",
    "GenCoroutineTest.test_async_await": "PASSED",
    "GenCoroutineTest.test_async_await_mixed_multi_native_future": "PASSED",
    "GenCoroutineTest.test_async_early_return": "PASSED",
    "GenCoroutineTest.test_async_gen_return": "PASSED",
    "GenCoroutineTest.test_async_raise": "PASSED",
    "GenCoroutineTest.test_async_return": "PASSED",
    "GenCoroutineTest.test_async_return_no_value": "PASSED",
    "GenCoroutineTest.test_async_with_timeout": "PASSED",
    "GenCoroutineTest.test_asyncio_future_debug_info": "PASSED",
    "GenCoroutineTest.test_asyncio_gather": "PASSED",
    "GenCoroutineTest.test_asyncio_sleep_zero": "PASSED",
    "GenCoroutineTest.test_attributes": "PASSED",
    "GenCoroutineTest.test_coroutine_refcounting": "PASSED",
    "GenCoroutineTest.test_is_coroutine_function": "PASSED",
    "GenCoroutineTest.test_moment": "PASSED",
    "GenCoroutineTest.test_py3_leak_exception_context": "PASSED",
    "GenCoroutineTest.test_replace_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sleep": "PASSED",
    "GenCoroutineTest.test_swallow_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sync_gen_return": "PASSED",
    "GenCoroutineTest.test_sync_raise": "PASSED",
    "GenCoroutineTest.test_sync_return": "PASSED",
    "GenCoroutineTest.test_sync_return_no_value": "PASSED",
    "GenWebTest.test_async_prepare_error_handler": "PASSED",
    "GenWebTest.test_coroutine_sequence_handler": "PASSED",
    "GenWebTest.test_coroutine_unfinished_sequence_handler": "PASSED",
    "GenWebTest.test_native_coroutine_handler": "PASSED",
    "GenWebTest.test_undecorated_coroutines": "PASSED",
    "RunnerGCTest.test_gc": "PASSED",
    "RunnerGCTest.test_gc_infinite_async_await": "PASSED",
    "RunnerGCTest.test_gc_infinite_coro": "PASSED",
    "RunnerGCTest.test_multi_moment": "PASSED",
    "WaitIteratorTest.test_already_done": "PASSED",
    "WaitIteratorTest.test_empty_iterator": "PASSED",
    "WaitIteratorTest.test_iterator": "PASSED",
    "WaitIteratorTest.test_iterator_async_await": "PASSED",
    "WaitIteratorTest.test_no_ref": "PASSED",
    "WithTimeoutTest.test_already_resolved": "PASSED",
    "WithTimeoutTest.test_completed_concurrent_future": "PASSED",
    "WithTimeoutTest.test_completes_before_timeout": "PASSED",
    "WithTimeoutTest.test_fails_before_timeout": "PASSED",
    "WithTimeoutTest.test_normal_concurrent_future": "PASSED",
    "WithTimeoutTest.test_timeout": "PASSED",
    "WithTimeoutTest.test_timeout_concurrent_future": "PASSED"
}
diff --git a/tornado/gen.py b/tornado/gen.py
index 1946ab91..f3e6e72f 100644
--- a/tornado/gen.py
+++ b/tornado/gen.py
@@ -743,7 +743,7 @@ class Runner(object):
         self.running = False
         self.finished = False
         self.io_loop = IOLoop.current()
-        if self.handle_yield(first_yielded):
+        if self.ctx_run(self.handle_yield, first_yielded):
             gen = result_future = first_yielded = None  # type: ignore
             self.ctx_run(self.run)
 

{"tornado/gen.py": "\"\"\"``tornado.gen`` implements generator-based coroutines.\n\n.. note::\n\n   The \"decorator and generator\" approach in this module is a\n   precursor to native coroutines (using ``async def`` and ``await``)\n   which were introduced in Python 3.5. Applications that do not\n   require compatibility with older versions of Python should use\n   native coroutines instead. Some parts of this module are still\n   useful with native coroutines, notably `multi`, `sleep`,\n   `WaitIterator`, and `with_timeout`. Some of these functions have\n   counterparts in the `asyncio` module which may be used as well,\n   although the two may not necessarily be 100% compatible.\n\nCoroutines provide an easier way to work in an asynchronous\nenvironment than chaining callbacks. Code using coroutines is\ntechnically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, here's a coroutine-based handler:\n\n.. testcode::\n\n    class GenAsyncHandler(RequestHandler):\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\n.. testoutput::\n   :hide:\n\nAsynchronous functions in Tornado return an ``Awaitable`` or `.Future`;\nyielding this object returns its result.\n\nYou can also yield a list or dict of other yieldable objects, which\nwill be started at the same time and run in parallel; a list or dict\nof results will be returned when they are all finished:\n\n.. testcode::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n        response_dict = yield dict(response3=http_client.fetch(url3),\n                                   response4=http_client.fetch(url4))\n        response3 = response_dict['response3']\n        response4 = response_dict['response4']\n\n.. testoutput::\n   :hide:\n\nIf ``tornado.platform.twisted`` is imported, it is also possible to\nyield Twisted's ``Deferred`` objects. See the `convert_yielded`\nfunction to extend this mechanism.\n\n.. versionchanged:: 3.2\n   Dict support added.\n\n.. versionchanged:: 4.1\n   Support added for yielding ``asyncio`` Futures and Twisted Deferreds\n   via ``singledispatch``.\n\n\"\"\"\nimport asyncio\nimport builtins\nimport collections\nfrom collections.abc import Generator\nimport concurrent.futures\nimport datetime\nimport functools\nfrom functools import singledispatch\nfrom inspect import isawaitable\nimport sys\nimport types\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n    future_set_result_unless_cancelled,\n)\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import app_log\nfrom tornado.util import TimeoutError\n\ntry:\n    import contextvars\nexcept ImportError:\n    contextvars = None  # type: ignore\n\nimport typing\nfrom typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload\n\nif typing.TYPE_CHECKING:\n    from typing import Sequence, Deque, Optional, Set, Iterable  # noqa: F401\n\n_T = typing.TypeVar(\"_T\")\n\n_Yieldable = Union[\n    None, Awaitable, List[Awaitable], Dict[Any, Awaitable], concurrent.futures.Future\n]\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef _value_from_stopiteration(e: Union[StopIteration, \"Return\"]) -> Any:\n    try:\n        # StopIteration has a value attribute beginning in py33.\n        # So does our Return class.\n        return e.value\n    except AttributeError:\n        pass\n    try:\n        # Cython backports coroutine functionality by putting the value in\n        # e.args[0].\n        return e.args[0]\n    except (AttributeError, IndexError):\n        return None\n\n\ndef _create_future() -> Future:\n    future = Future()  # type: Future\n    # Fixup asyncio debug info by removing extraneous stack entries\n    source_traceback = getattr(future, \"_source_traceback\", ())\n    while source_traceback:\n        # Each traceback entry is equivalent to a\n        # (filename, self.lineno, self.name, self.line) tuple\n        filename = source_traceback[-1][0]\n        if filename == __file__:\n            del source_traceback[-1]\n        else:\n            break\n    return future\n\n\ndef _fake_ctx_run(f: Callable[..., _T], *args: Any, **kw: Any) -> _T:\n    return f(*args, **kw)\n\n\n@overload\ndef coroutine(\n    func: Callable[..., \"Generator[Any, Any, _T]\"]\n) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\n@overload\ndef coroutine(func: Callable[..., _T]) -> Callable[..., \"Future[_T]\"]:\n    ...\n\n\ndef coroutine(\n    func: Union[Callable[..., \"Generator[Any, Any, _T]\"], Callable[..., _T]]\n) -> Callable[..., \"Future[_T]\"]:\n    \"\"\"Decorator for asynchronous generators.\n\n    For compatibility with older versions of Python, coroutines may\n    also \"return\" by raising the special exception `Return(value)\n    <Return>`.\n\n    Functions with this decorator return a `.Future`.\n\n    .. warning::\n\n       When exceptions occur inside a coroutine, the exception\n       information will be stored in the `.Future` object. You must\n       examine the result of the `.Future` object, or the exception\n       may go unnoticed by your code. This means yielding the function\n       if called from another coroutine, using something like\n       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`\n       to `.IOLoop.add_future`.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed. Use the returned\n       awaitable object instead.\n\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        # type: (*Any, **Any) -> Future[_T]\n        # This function is type-annotated with a comment to work around\n        # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in\n        future = _create_future()\n        if contextvars is not None:\n            ctx_run = contextvars.copy_context().run  # type: Callable\n        else:\n            ctx_run = _fake_ctx_run\n        try:\n            result = ctx_run(func, *args, **kwargs)\n        except (Return, StopIteration) as e:\n            result = _value_from_stopiteration(e)\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n            try:\n                return future\n            finally:\n                # Avoid circular references\n                future = None  # type: ignore\n        else:\n            if isinstance(result, Generator):\n                # Inline the first iteration of Runner.run.  This lets us\n                # avoid the cost of creating a Runner when the coroutine\n                # never actually yields, which in turn allows us to\n                # use \"optional\" coroutines in critical path code without\n                # performance penalty for the synchronous case.\n                try:\n                    yielded = ctx_run(next, result)\n                except (StopIteration, Return) as e:\n                    future_set_result_unless_cancelled(\n                        future, _value_from_stopiteration(e)\n                    )\n                except Exception:\n                    future_set_exc_info(future, sys.exc_info())\n                else:\n                    # Provide strong references to Runner objects as long\n                    # as their result future objects also have strong\n                    # references (typically from the parent coroutine's\n                    # Runner). This keeps the coroutine's Runner alive.\n                    # We do this by exploiting the public API\n                    # add_done_callback() instead of putting a private\n                    # attribute on the Future.\n                    # (GitHub issues #1769, #2229).\n                    runner = Runner(ctx_run, result, future, yielded)\n                    future.add_done_callback(lambda _: runner)\n                yielded = None\n                try:\n                    return future\n                finally:\n                    # Subtle memory optimization: if next() raised an exception,\n                    # the future's exc_info contains a traceback which\n                    # includes this stack frame.  This creates a cycle,\n                    # which will be collected at the next full GC but has\n                    # been shown to greatly increase memory usage of\n                    # benchmarks (relative to the refcount-based scheme\n                    # used in the absence of cycles).  We can avoid the\n                    # cycle by clearing the local variable after we return it.\n                    future = None  # type: ignore\n        future_set_result_unless_cancelled(future, result)\n        return future\n\n    wrapper.__wrapped__ = func  # type: ignore\n    wrapper.__tornado_coroutine__ = True  # type: ignore\n    return wrapper\n\n\ndef is_coroutine_function(func: Any) -> bool:\n    \"\"\"Return whether *func* is a coroutine function, i.e. a function\n    wrapped with `~.gen.coroutine`.\n\n    .. versionadded:: 4.5\n    \"\"\"\n    return getattr(func, \"__tornado_coroutine__\", False)\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n\n    def __init__(self, value: Any = None) -> None:\n        super().__init__()\n        self.value = value\n        # Cython recognizes subclasses of StopIteration with a .args tuple.\n        self.args = (value,)\n\n\nclass WaitIterator(object):\n    \"\"\"Provides an iterator to yield the results of awaitables as they finish.\n\n    Yielding a set of awaitables like this:\n\n    ``results = yield [awaitable1, awaitable2]``\n\n    pauses the coroutine until both ``awaitable1`` and ``awaitable2``\n    return, and then restarts the coroutine with the results of both\n    awaitables. If either awaitable raises an exception, the\n    expression will raise that exception and all the results will be\n    lost.\n\n    If you need to get the result of each awaitable as soon as possible,\n    or if you need the result of some awaitables even if others produce\n    errors, you can use ``WaitIterator``::\n\n      wait_iterator = gen.WaitIterator(awaitable1, awaitable2)\n      while not wait_iterator.done():\n          try:\n              result = yield wait_iterator.next()\n          except Exception as e:\n              print(\"Error {} from {}\".format(e, wait_iterator.current_future))\n          else:\n              print(\"Result {} received from {} at {}\".format(\n                  result, wait_iterator.current_future,\n                  wait_iterator.current_index))\n\n    Because results are returned as soon as they are available the\n    output from the iterator *will not be in the same order as the\n    input arguments*. If you need to know which future produced the\n    current result, you can use the attributes\n    ``WaitIterator.current_future``, or ``WaitIterator.current_index``\n    to get the index of the awaitable from the input list. (if keyword\n    arguments were used in the construction of the `WaitIterator`,\n    ``current_index`` will use the corresponding keyword).\n\n    On Python 3.5, `WaitIterator` implements the async iterator\n    protocol, so it can be used with the ``async for`` statement (note\n    that in this version the entire iteration is aborted if any value\n    raises an exception, while the previous example can continue past\n    individual errors)::\n\n      async for result in gen.WaitIterator(future1, future2):\n          print(\"Result {} received from {} at {}\".format(\n              result, wait_iterator.current_future,\n              wait_iterator.current_index))\n\n    .. versionadded:: 4.1\n\n    .. versionchanged:: 4.3\n       Added ``async for`` support in Python 3.5.\n\n    \"\"\"\n\n    _unfinished = {}  # type: Dict[Future, Union[int, str]]\n\n    def __init__(self, *args: Future, **kwargs: Future) -> None:\n        if args and kwargs:\n            raise ValueError(\"You must provide args or kwargs, not both\")\n\n        if kwargs:\n            self._unfinished = dict((f, k) for (k, f) in kwargs.items())\n            futures = list(kwargs.values())  # type: Sequence[Future]\n        else:\n            self._unfinished = dict((f, i) for (i, f) in enumerate(args))\n            futures = args\n\n        self._finished = collections.deque()  # type: Deque[Future]\n        self.current_index = None  # type: Optional[Union[str, int]]\n        self.current_future = None  # type: Optional[Future]\n        self._running_future = None  # type: Optional[Future]\n\n        for future in futures:\n            future_add_done_callback(future, self._done_callback)\n\n    def done(self) -> bool:\n        \"\"\"Returns True if this iterator has no more results.\"\"\"\n        if self._finished or self._unfinished:\n            return False\n        # Clear the 'current' values when iteration is done.\n        self.current_index = self.current_future = None\n        return True\n\n    def next(self) -> Future:\n        \"\"\"Returns a `.Future` that will yield the next available result.\n\n        Note that this `.Future` will not be the same object as any of\n        the inputs.\n        \"\"\"\n        self._running_future = Future()\n\n        if self._finished:\n            return self._return_result(self._finished.popleft())\n\n        return self._running_future\n\n    def _done_callback(self, done: Future) -> None:\n        if self._running_future and not self._running_future.done():\n            self._return_result(done)\n        else:\n            self._finished.append(done)\n\n    def _return_result(self, done: Future) -> Future:\n        \"\"\"Called set the returned future's state that of the future\n        we yielded, and set the current future for the iterator.\n        \"\"\"\n        if self._running_future is None:\n            raise Exception(\"no future is running\")\n        chain_future(done, self._running_future)\n\n        res = self._running_future\n        self._running_future = None\n        self.current_future = done\n        self.current_index = self._unfinished.pop(done)\n\n        return res\n\n    def __aiter__(self) -> typing.AsyncIterator:\n        return self\n\n    def __anext__(self) -> Future:\n        if self.done():\n            # Lookup by name to silence pyflakes on older versions.\n            raise getattr(builtins, \"StopAsyncIteration\")()\n        return self.next()\n\n\ndef multi(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    ``children`` may either be a list or a dict whose values are\n    yieldable objects. ``multi()`` returns a new yieldable\n    object that resolves to a parallel structure containing their\n    results. If ``children`` is a list, the result is a list of\n    results in the same order; if it is a dict, the result is a dict\n    with the same keys.\n\n    That is, ``results = yield multi(list_of_futures)`` is equivalent\n    to::\n\n        results = []\n        for future in list_of_futures:\n            results.append(yield future)\n\n    If any children raise exceptions, ``multi()`` will raise the first\n    one. All others will be logged, unless they are of types\n    contained in the ``quiet_exceptions`` argument.\n\n    In a ``yield``-based coroutine, it is not normally necessary to\n    call this function directly, since the coroutine runner will\n    do it automatically when a list or dict is yielded. However,\n    it is necessary in ``await``-based coroutines, or to pass\n    the ``quiet_exceptions`` argument.\n\n    This function is available under the names ``multi()`` and ``Multi()``\n    for historical reasons.\n\n    Cancelling a `.Future` returned by ``multi()`` does not cancel its\n    children. `asyncio.gather` is similar to ``multi()``, but it does\n    cancel its children.\n\n    .. versionchanged:: 4.2\n       If multiple yieldables fail, any exceptions after the first\n       (which is raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. versionchanged:: 4.3\n       Replaced the class ``Multi`` and the function ``multi_future``\n       with a unified function ``multi``. Added support for yieldables\n       other than ``YieldPoint`` and `.Future`.\n\n    \"\"\"\n    return multi_future(children, quiet_exceptions=quiet_exceptions)\n\n\nMulti = multi\n\n\ndef multi_future(\n    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> \"Union[Future[List], Future[Dict]]\":\n    \"\"\"Wait for multiple asynchronous futures in parallel.\n\n    Since Tornado 6.0, this function is exactly the same as `multi`.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.2\n       If multiple ``Futures`` fail, any exceptions after the first (which is\n       raised) will be logged. Added the ``quiet_exceptions``\n       argument to suppress this logging for selected exception types.\n\n    .. deprecated:: 4.3\n       Use `multi` instead.\n    \"\"\"\n    if isinstance(children, dict):\n        keys = list(children.keys())  # type: Optional[List]\n        children_seq = children.values()  # type: Iterable\n    else:\n        keys = None\n        children_seq = children\n    children_futs = list(map(convert_yielded, children_seq))\n    assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs)\n    unfinished_children = set(children_futs)\n\n    future = _create_future()\n    if not children_futs:\n        future_set_result_unless_cancelled(future, {} if keys is not None else [])\n\n    def callback(fut: Future) -> None:\n        unfinished_children.remove(fut)\n        if not unfinished_children:\n            result_list = []\n            for f in children_futs:\n                try:\n                    result_list.append(f.result())\n                except Exception as e:\n                    if future.done():\n                        if not isinstance(e, quiet_exceptions):\n                            app_log.error(\n                                \"Multiple exceptions in yield list\", exc_info=True\n                            )\n                    else:\n                        future_set_exc_info(future, sys.exc_info())\n            if not future.done():\n                if keys is not None:\n                    future_set_result_unless_cancelled(\n                        future, dict(zip(keys, result_list))\n                    )\n                else:\n                    future_set_result_unless_cancelled(future, result_list)\n\n    listening = set()  # type: Set[Future]\n    for f in children_futs:\n        if f not in listening:\n            listening.add(f)\n            future_add_done_callback(f, callback)\n    return future\n\n\ndef maybe_future(x: Any) -> Future:\n    \"\"\"Converts ``x`` into a `.Future`.\n\n    If ``x`` is already a `.Future`, it is simply returned; otherwise\n    it is wrapped in a new `.Future`.  This is suitable for use as\n    ``result = yield gen.maybe_future(f())`` when you don't know whether\n    ``f()`` returns a `.Future` or not.\n\n    .. deprecated:: 4.3\n       This function only handles ``Futures``, not other yieldable objects.\n       Instead of `maybe_future`, check for the non-future result types\n       you expect (often just ``None``), and ``yield`` anything unknown.\n    \"\"\"\n    if is_future(x):\n        return x\n    else:\n        fut = _create_future()\n        fut.set_result(x)\n        return fut\n\n\ndef with_timeout(\n    timeout: Union[float, datetime.timedelta],\n    future: _Yieldable,\n    quiet_exceptions: \"Union[Type[Exception], Tuple[Type[Exception], ...]]\" = (),\n) -> Future:\n    \"\"\"Wraps a `.Future` (or other yieldable object) in a timeout.\n\n    Raises `tornado.util.TimeoutError` if the input future does not\n    complete before ``timeout``, which may be specified in any form\n    allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or\n    an absolute time relative to `.IOLoop.time`)\n\n    If the wrapped `.Future` fails after it has timed out, the exception\n    will be logged unless it is either of a type contained in\n    ``quiet_exceptions`` (which may be an exception type or a sequence of\n    types), or an ``asyncio.CancelledError``.\n\n    The wrapped `.Future` is not canceled when the timeout expires,\n    permitting it to be reused. `asyncio.wait_for` is similar to this\n    function but it does cancel the wrapped `.Future` on timeout.\n\n    .. versionadded:: 4.0\n\n    .. versionchanged:: 4.1\n       Added the ``quiet_exceptions`` argument and the logging of unhandled\n       exceptions.\n\n    .. versionchanged:: 4.4\n       Added support for yieldable objects other than `.Future`.\n\n    .. versionchanged:: 6.0.3\n       ``asyncio.CancelledError`` is now always considered \"quiet\".\n\n    .. versionchanged:: 6.2\n       ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n\n    \"\"\"\n    # It's tempting to optimize this by cancelling the input future on timeout\n    # instead of creating a new one, but A) we can't know if we are the only\n    # one waiting on the input future, so cancelling it might disrupt other\n    # callers and B) concurrent futures can only be cancelled while they are\n    # in the queue, so cancellation cannot reliably bound our waiting time.\n    future_converted = convert_yielded(future)\n    result = _create_future()\n    chain_future(future_converted, result)\n    io_loop = IOLoop.current()\n\n    def error_callback(future: Future) -> None:\n        try:\n            future.result()\n        except asyncio.CancelledError:\n            pass\n        except Exception as e:\n            if not isinstance(e, quiet_exceptions):\n                app_log.error(\n                    \"Exception in Future %r after timeout\", future, exc_info=True\n                )\n\n    def timeout_callback() -> None:\n        if not result.done():\n            result.set_exception(TimeoutError(\"Timeout\"))\n        # In case the wrapped future goes on to fail, log it.\n        future_add_done_callback(future_converted, error_callback)\n\n    timeout_handle = io_loop.add_timeout(timeout, timeout_callback)\n    if isinstance(future_converted, Future):\n        # We know this future will resolve on the IOLoop, so we don't\n        # need the extra thread-safety of IOLoop.add_future (and we also\n        # don't care about StackContext here.\n        future_add_done_callback(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    else:\n        # concurrent.futures.Futures may resolve on any thread, so we\n        # need to route them back to the IOLoop.\n        io_loop.add_future(\n            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)\n        )\n    return result\n\n\ndef sleep(duration: float) -> \"Future[None]\":\n    \"\"\"Return a `.Future` that resolves after the given number of seconds.\n\n    When used with ``yield`` in a coroutine, this is a non-blocking\n    analogue to `time.sleep` (which should not be used in coroutines\n    because it is blocking)::\n\n        yield gen.sleep(0.5)\n\n    Note that calling this function on its own does nothing; you must\n    wait on the `.Future` it returns (usually by yielding it).\n\n    .. versionadded:: 4.1\n    \"\"\"\n    f = _create_future()\n    IOLoop.current().call_later(\n        duration, lambda: future_set_result_unless_cancelled(f, None)\n    )\n    return f\n\n\nclass _NullFuture(object):\n    \"\"\"_NullFuture resembles a Future that finished with a result of None.\n\n    It's not actually a `Future` to avoid depending on a particular event loop.\n    Handled as a special case in the coroutine runner.\n\n    We lie and tell the type checker that a _NullFuture is a Future so\n    we don't have to leak _NullFuture into lots of public APIs. But\n    this means that the type checker can't warn us when we're passing\n    a _NullFuture into a code path that doesn't understand what to do\n    with it.\n    \"\"\"\n\n    def result(self) -> None:\n        return None\n\n    def done(self) -> bool:\n        return True\n\n\n# _null_future is used as a dummy value in the coroutine runner. It differs\n# from moment in that moment always adds a delay of one IOLoop iteration\n# while _null_future is processed as soon as possible.\n_null_future = typing.cast(Future, _NullFuture())\n\nmoment = typing.cast(Future, _NullFuture())\nmoment.__doc__ = \"\"\"A special object which may be yielded to allow the IOLoop to run for\none iteration.\n\nThis is not needed in normal use but it can be helpful in long-running\ncoroutines that are likely to yield Futures that are ready instantly.\n\nUsage: ``yield gen.moment``\n\nIn native coroutines, the equivalent of ``yield gen.moment`` is\n``await asyncio.sleep(0)``.\n\n.. versionadded:: 4.0\n\n.. deprecated:: 4.5\n   ``yield None`` (or ``yield`` with no argument) is now equivalent to\n    ``yield gen.moment``.\n\"\"\"\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.coroutine`.\n\n    Maintains information about pending callbacks and their results.\n\n    The results of the generator are stored in ``result_future`` (a\n    `.Future`)\n    \"\"\"\n\n    def __init__(\n        self,\n        ctx_run: Callable,\n        gen: \"Generator[_Yieldable, Any, _T]\",\n        result_future: \"Future[_T]\",\n        first_yielded: _Yieldable,\n    ) -> None:\n        self.ctx_run = ctx_run\n        self.gen = gen\n        self.result_future = result_future\n        self.future = _null_future  # type: Union[None, Future]\n        self.running = False\n        self.finished = False\n        self.io_loop = IOLoop.current()\n        if self.handle_yield(first_yielded):\n            gen = result_future = first_yielded = None  # type: ignore\n            self.ctx_run(self.run)\n\n    def run(self) -> None:\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                future = self.future\n                if future is None:\n                    raise Exception(\"No pending future\")\n                if not future.done():\n                    return\n                self.future = None\n                try:\n                    exc_info = None\n\n                    try:\n                        value = future.result()\n                    except Exception:\n                        exc_info = sys.exc_info()\n                    future = None\n\n                    if exc_info is not None:\n                        try:\n                            yielded = self.gen.throw(*exc_info)  # type: ignore\n                        finally:\n                            # Break up a reference to itself\n                            # for faster GC on CPython.\n                            exc_info = None\n                    else:\n                        yielded = self.gen.send(value)\n\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_result_unless_cancelled(\n                        self.result_future, _value_from_stopiteration(e)\n                    )\n                    self.result_future = None  # type: ignore\n                    return\n                except Exception:\n                    self.finished = True\n                    self.future = _null_future\n                    future_set_exc_info(self.result_future, sys.exc_info())\n                    self.result_future = None  # type: ignore\n                    return\n                if not self.handle_yield(yielded):\n                    return\n                yielded = None\n        finally:\n            self.running = False\n\n    def handle_yield(self, yielded: _Yieldable) -> bool:\n        try:\n            self.future = convert_yielded(yielded)\n        except BadYieldError:\n            self.future = Future()\n            future_set_exc_info(self.future, sys.exc_info())\n\n        if self.future is moment:\n            self.io_loop.add_callback(self.ctx_run, self.run)\n            return False\n        elif self.future is None:\n            raise Exception(\"no pending future\")\n        elif not self.future.done():\n\n            def inner(f: Any) -> None:\n                # Break a reference cycle to speed GC.\n                f = None  # noqa: F841\n                self.ctx_run(self.run)\n\n            self.io_loop.add_future(self.future, inner)\n            return False\n        return True\n\n    def handle_exception(\n        self, typ: Type[Exception], value: Exception, tb: types.TracebackType\n    ) -> bool:\n        if not self.running and not self.finished:\n            self.future = Future()\n            future_set_exc_info(self.future, (typ, value, tb))\n            self.ctx_run(self.run)\n            return True\n        else:\n            return False\n\n\n# Convert Awaitables into Futures.\ntry:\n    _wrap_awaitable = asyncio.ensure_future\nexcept AttributeError:\n    # asyncio.ensure_future was introduced in Python 3.4.4, but\n    # Debian jessie still ships with 3.4.2 so try the old name.\n    _wrap_awaitable = getattr(asyncio, \"async\")\n\n\ndef convert_yielded(yielded: _Yieldable) -> Future:\n    \"\"\"Convert a yielded object into a `.Future`.\n\n    The default implementation accepts lists, dictionaries, and\n    Futures. This has the side effect of starting any coroutines that\n    did not start themselves, similar to `asyncio.ensure_future`.\n\n    If the `~functools.singledispatch` library is available, this function\n    may be extended to support additional types. For example::\n\n        @convert_yielded.register(asyncio.Future)\n        def _(asyncio_future):\n            return tornado.platform.asyncio.to_tornado_future(asyncio_future)\n\n    .. versionadded:: 4.1\n\n    \"\"\"\n    if yielded is None or yielded is moment:\n        return moment\n    elif yielded is _null_future:\n        return _null_future\n    elif isinstance(yielded, (list, dict)):\n        return multi(yielded)  # type: ignore\n    elif is_future(yielded):\n        return typing.cast(Future, yielded)\n    elif isawaitable(yielded):\n        return _wrap_awaitable(yielded)  # type: ignore\n    else:\n        raise BadYieldError(\"yielded unknown object %r\" % (yielded,))\n\n\nconvert_yielded = singledispatch(convert_yielded)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** ContextVars Context Not Propagated to First Yield in Native Coroutines

**Description:**
When using native `async` functions with coroutines, the `contextvars.Context` is not correctly propagated to the first yield point. This results in a `LookupError` when attempting to access context variables within the coroutine after the first yield.

**Example Code:**
```python
import contextvars
import asyncio

ctx_var = contextvars.ContextVar('ctx_var')

async def native_async_function():
    print(ctx_var.get())

def run_coroutine():
    ctx_var.set(10)
    asyncio.run(native_async_function())

run_coroutine()
```
**Expected Behavior:**
The context variable `ctx_var` should retain its value (`10`) within the `native_async_function` after yielding, allowing it to be accessed without errors.

**Actual Behavior:**
A `LookupError` is raised when `ctx_var.get()` is called inside `native_async_function`, indicating that the context variable is not available in the coroutine's context after the first yield.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` implements generator-based coroutines.

.. note::

   The "decorator and generator" approach in this module is a
   precursor to native coroutines (using ``async def`` and ``await``)
   which were introduced in Python 3.5. Applications that do not
   require compatibility with older versions of Python should use
   native coroutines instead. Some parts of this module are still
   useful with native coroutines, notably `multi`, `sleep`,
   `WaitIterator`, and `with_timeout`. Some of these functions have
   counterparts in the `asyncio` module which may be used as well,
   although the two may not necessarily be 100% compatible.

Coroutines provide an easier way to work in an asynchronous
environment than chaining callbacks. Code using coroutines is
technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, here's a coroutine-based handler:

.. testcode::

    class GenAsyncHandler(RequestHandler):
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            response = yield http_client.fetch("http://example.com")
            do_something_with_response(response)
            self.render("template.html")

.. testoutput::
   :hide:

Asynchronous functions in Tornado return an ``Awaitable`` or `.Future`;
yielding this object returns its result.

You can also yield a list or dict of other yieldable objects, which
will be started at the same time and run in parallel; a list or dict
of results will be returned when they are all finished:

.. testcode::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]
        response_dict = yield dict(response3=http_client.fetch(url3),
                                   response4=http_client.fetch(url4))
        response3 = response_dict['response3']
        response4 = response_dict['response4']

.. testoutput::
   :hide:

If ``tornado.platform.twisted`` is imported, it is also possible to
yield Twisted's ``Deferred`` objects. See the `convert_yielded`
function to extend this mechanism.

.. versionchanged:: 3.2
   Dict support added.

.. versionchanged:: 4.1
   Support added for yielding ``asyncio`` Futures and Twisted Deferreds
   via ``singledispatch``.

"""
import asyncio
import builtins
import collections
from collections.abc import Generator
import concurrent.futures
import datetime
import functools
from functools import singledispatch
from inspect import isawaitable
import sys
import types

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
    future_set_result_unless_cancelled,
)
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado.util import TimeoutError

try:
    import contextvars
except ImportError:
    contextvars = None  # type: ignore

import typing
from typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload

if typing.TYPE_CHECKING:
    from typing import Sequence, Deque, Optional, Set, Iterable  # noqa: F401

_T = typing.TypeVar("_T")

_Yieldable = Union[
    None, Awaitable, List[Awaitable], Dict[Any, Awaitable], concurrent.futures.Future
]


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


def _value_from_stopiteration(e: Union[StopIteration, "Return"]) -> Any:
    try:
        # StopIteration has a value attribute beginning in py33.
        # So does our Return class.
        return e.value
    except AttributeError:
        pass
    try:
        # Cython backports coroutine functionality by putting the value in
        # e.args[0].
        return e.args[0]
    except (AttributeError, IndexError):
        return None


def _create_future() -> Future:
    future = Future()  # type: Future
    # Fixup asyncio debug info by removing extraneous stack entries
    source_traceback = getattr(future, "_source_traceback", ())
    while source_traceback:
        # Each traceback entry is equivalent to a
        # (filename, self.lineno, self.name, self.line) tuple
        filename = source_traceback[-1][0]
        if filename == __file__:
            del source_traceback[-1]
        else:
            break
    return future


def _fake_ctx_run(f: Callable[..., _T], *args: Any, **kw: Any) -> _T:
    return f(*args, **kw)


@overload
def coroutine(
    func: Callable[..., "Generator[Any, Any, _T]"]
) -> Callable[..., "Future[_T]"]:
    ...


@overload
def coroutine(func: Callable[..., _T]) -> Callable[..., "Future[_T]"]:
    ...


def coroutine(
    func: Union[Callable[..., "Generator[Any, Any, _T]"], Callable[..., _T]]
) -> Callable[..., "Future[_T]"]:
    """Decorator for asynchronous generators.

    For compatibility with older versions of Python, coroutines may
    also "return" by raising the special exception `Return(value)
    <Return>`.

    Functions with this decorator return a `.Future`.

    .. warning::

       When exceptions occur inside a coroutine, the exception
       information will be stored in the `.Future` object. You must
       examine the result of the `.Future` object, or the exception
       may go unnoticed by your code. This means yielding the function
       if called from another coroutine, using something like
       `.IOLoop.run_sync` for top-level calls, or passing the `.Future`
       to `.IOLoop.add_future`.

    .. versionchanged:: 6.0

       The ``callback`` argument was removed. Use the returned
       awaitable object instead.

    """

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # type: (*Any, **Any) -> Future[_T]
        # This function is type-annotated with a comment to work around
        # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in
        future = _create_future()
        if contextvars is not None:
            ctx_run = contextvars.copy_context().run  # type: Callable
        else:
            ctx_run = _fake_ctx_run
        try:
            result = ctx_run(func, *args, **kwargs)
        except (Return, StopIteration) as e:
            result = _value_from_stopiteration(e)
        except Exception:
            future_set_exc_info(future, sys.exc_info())
            try:
                return future
            finally:
                # Avoid circular references
                future = None  # type: ignore
        else:
            if isinstance(result, Generator):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    yielded = ctx_run(next, result)
                except (StopIteration, Return) as e:
                    future_set_result_unless_cancelled(
                        future, _value_from_stopiteration(e)
                    )
                except Exception:
                    future_set_exc_info(future, sys.exc_info())
                else:
                    # Provide strong references to Runner objects as long
                    # as their result future objects also have strong
                    # references (typically from the parent coroutine's
                    # Runner). This keeps the coroutine's Runner alive.
                    # We do this by exploiting the public API
                    # add_done_callback() instead of putting a private
                    # attribute on the Future.
                    # (GitHub issues #1769, #2229).
                    runner = Runner(ctx_run, result, future, yielded)
                    future.add_done_callback(lambda _: runner)
                yielded = None
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None  # type: ignore
        future_set_result_unless_cancelled(future, result)
        return future

    wrapper.__wrapped__ = func  # type: ignore
    wrapper.__tornado_coroutine__ = True  # type: ignore
    return wrapper


def is_coroutine_function(func: Any) -> bool:
    """Return whether *func* is a coroutine function, i.e. a function
    wrapped with `~.gen.coroutine`.

    .. versionadded:: 4.5
    """
    return getattr(func, "__tornado_coroutine__", False)


class Return(Exception):
    """Special exception to return a value from a `coroutine`.

    If this exception is raised, its value argument is used as the
    result of the coroutine::

        @gen.coroutine
        def fetch_json(url):
            response = yield AsyncHTTPClient().fetch(url)
            raise gen.Return(json_decode(response.body))

    In Python 3.3, this exception is no longer necessary: the ``return``
    statement can be used directly to return a value (previously
    ``yield`` and ``return`` with a value could not be combined in the
    same function).

    By analogy with the return statement, the value argument is optional,
    but it is never necessary to ``raise gen.Return()``.  The ``return``
    statement can be used with no arguments instead.
    """

    def __init__(self, value: Any = None) -> None:
        super().__init__()
        self.value = value
        # Cython recognizes subclasses of StopIteration with a .args tuple.
        self.args = (value,)


class WaitIterator(object):
    """Provides an iterator to yield the results of awaitables as they finish.

    Yielding a set of awaitables like this:

    ``results = yield [awaitable1, awaitable2]``

    pauses the coroutine until both ``awaitable1`` and ``awaitable2``
    return, and then restarts the coroutine with the results of both
    awaitables. If either awaitable raises an exception, the
    expression will raise that exception and all the results will be
    lost.

    If you need to get the result of each awaitable as soon as possible,
    or if you need the result of some awaitables even if others produce
    errors, you can use ``WaitIterator``::

      wait_iterator = gen.WaitIterator(awaitable1, awaitable2)
      while not wait_iterator.done():
          try:
              result = yield wait_iterator.next()
          except Exception as e:
              print("Error {} from {}".format(e, wait_iterator.current_future))
          else:
              print("Result {} received from {} at {}".format(
                  result, wait_iterator.current_future,
                  wait_iterator.current_index))

    Because results are returned as soon as they are available the
    output from the iterator *will not be in the same order as the
    input arguments*. If you need to know which future produced the
    current result, you can use the attributes
    ``WaitIterator.current_future``, or ``WaitIterator.current_index``
    to get the index of the awaitable from the input list. (if keyword
    arguments were used in the construction of the `WaitIterator`,
    ``current_index`` will use the corresponding keyword).

    On Python 3.5, `WaitIterator` implements the async iterator
    protocol, so it can be used with the ``async for`` statement (note
    that in this version the entire iteration is aborted if any value
    raises an exception, while the previous example can continue past
    individual errors)::

      async for result in gen.WaitIterator(future1, future2):
          print("Result {} received from {} at {}".format(
              result, wait_iterator.current_future,
              wait_iterator.current_index))

    .. versionadded:: 4.1

    .. versionchanged:: 4.3
       Added ``async for`` support in Python 3.5.

    """

    _unfinished = {}  # type: Dict[Future, Union[int, str]]

    def __init__(self, *args: Future, **kwargs: Future) -> None:
        if args and kwargs:
            raise ValueError("You must provide args or kwargs, not both")

        if kwargs:
            self._unfinished = dict((f, k) for (k, f) in kwargs.items())
            futures = list(kwargs.values())  # type: Sequence[Future]
        else:
            self._unfinished = dict((f, i) for (i, f) in enumerate(args))
            futures = args

        self._finished = collections.deque()  # type: Deque[Future]
        self.current_index = None  # type: Optional[Union[str, int]]
        self.current_future = None  # type: Optional[Future]
        self._running_future = None  # type: Optional[Future]

        for future in futures:
            future_add_done_callback(future, self._done_callback)

    def done(self) -> bool:
        """Returns True if this iterator has no more results."""
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True

    def next(self) -> Future:
        """Returns a `.Future` that will yield the next available result.

        Note that this `.Future` will not be the same object as any of
        the inputs.
        """
        self._running_future = Future()

        if self._finished:
            return self._return_result(self._finished.popleft())

        return self._running_future

    def _done_callback(self, done: Future) -> None:
        if self._running_future and not self._running_future.done():
            self._return_result(done)
        else:
            self._finished.append(done)

    def _return_result(self, done: Future) -> Future:
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        if self._running_future is None:
            raise Exception("no future is running")
        chain_future(done, self._running_future)

        res = self._running_future
        self._running_future = None
        self.current_future = done
        self.current_index = self._unfinished.pop(done)

        return res

    def __aiter__(self) -> typing.AsyncIterator:
        return self

    def __anext__(self) -> Future:
        if self.done():
            # Lookup by name to silence pyflakes on older versions.
            raise getattr(builtins, "StopAsyncIteration")()
        return self.next()


def multi(
    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
    """Runs multiple asynchronous operations in parallel.

    ``children`` may either be a list or a dict whose values are
    yieldable objects. ``multi()`` returns a new yieldable
    object that resolves to a parallel structure containing their
    results. If ``children`` is a list, the result is a list of
    results in the same order; if it is a dict, the result is a dict
    with the same keys.

    That is, ``results = yield multi(list_of_futures)`` is equivalent
    to::

        results = []
        for future in list_of_futures:
            results.append(yield future)

    If any children raise exceptions, ``multi()`` will raise the first
    one. All others will be logged, unless they are of types
    contained in the ``quiet_exceptions`` argument.

    In a ``yield``-based coroutine, it is not normally necessary to
    call this function directly, since the coroutine runner will
    do it automatically when a list or dict is yielded. However,
    it is necessary in ``await``-based coroutines, or to pass
    the ``quiet_exceptions`` argument.

    This function is available under the names ``multi()`` and ``Multi()``
    for historical reasons.

    Cancelling a `.Future` returned by ``multi()`` does not cancel its
    children. `asyncio.gather` is similar to ``multi()``, but it does
    cancel its children.

    .. versionchanged:: 4.2
       If multiple yieldables fail, any exceptions after the first
       (which is raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. versionchanged:: 4.3
       Replaced the class ``Multi`` and the function ``multi_future``
       with a unified function ``multi``. Added support for yieldables
       other than ``YieldPoint`` and `.Future`.

    """
    return multi_future(children, quiet_exceptions=quiet_exceptions)


Multi = multi


def multi_future(
    children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
    """Wait for multiple asynchronous futures in parallel.

    Since Tornado 6.0, this function is exactly the same as `multi`.

    .. versionadded:: 4.0

    .. versionchanged:: 4.2
       If multiple ``Futures`` fail, any exceptions after the first (which is
       raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. deprecated:: 4.3
       Use `multi` instead.
    """
    if isinstance(children, dict):
        keys = list(children.keys())  # type: Optional[List]
        children_seq = children.values()  # type: Iterable
    else:
        keys = None
        children_seq = children
    children_futs = list(map(convert_yielded, children_seq))
    assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs)
    unfinished_children = set(children_futs)

    future = _create_future()
    if not children_futs:
        future_set_result_unless_cancelled(future, {} if keys is not None else [])

    def callback(fut: Future) -> None:
        unfinished_children.remove(fut)
        if not unfinished_children:
            result_list = []
            for f in children_futs:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            app_log.error(
                                "Multiple exceptions in yield list", exc_info=True
                            )
                    else:
                        future_set_exc_info(future, sys.exc_info())
            if not future.done():
                if keys is not None:
                    future_set_result_unless_cancelled(
                        future, dict(zip(keys, result_list))
                    )
                else:
                    future_set_result_unless_cancelled(future, result_list)

    listening = set()  # type: Set[Future]
    for f in children_futs:
        if f not in listening:
            listening.add(f)
            future_add_done_callback(f, callback)
    return future


def maybe_future(x: Any) -> Future:
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.

    .. deprecated:: 4.3
       This function only handles ``Futures``, not other yieldable objects.
       Instead of `maybe_future`, check for the non-future result types
       you expect (often just ``None``), and ``yield`` anything unknown.
    """
    if is_future(x):
        return x
    else:
        fut = _create_future()
        fut.set_result(x)
        return fut


def with_timeout(
    timeout: Union[float, datetime.timedelta],
    future: _Yieldable,
    quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> Future:
    """Wraps a `.Future` (or other yieldable object) in a timeout.

    Raises `tornado.util.TimeoutError` if the input future does not
    complete before ``timeout``, which may be specified in any form
    allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
    an absolute time relative to `.IOLoop.time`)

    If the wrapped `.Future` fails after it has timed out, the exception
    will be logged unless it is either of a type contained in
    ``quiet_exceptions`` (which may be an exception type or a sequence of
    types), or an ``asyncio.CancelledError``.

    The wrapped `.Future` is not canceled when the timeout expires,
    permitting it to be reused. `asyncio.wait_for` is similar to this
    function but it does cancel the wrapped `.Future` on timeout.

    .. versionadded:: 4.0

    .. versionchanged:: 4.1
       Added the ``quiet_exceptions`` argument and the logging of unhandled
       exceptions.

    .. versionchanged:: 4.4
       Added support for yieldable objects other than `.Future`.

    .. versionchanged:: 6.0.3
       ``asyncio.CancelledError`` is now always considered "quiet".

    .. versionchanged:: 6.2
       ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.

    """
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    future_converted = convert_yielded(future)
    result = _create_future()
    chain_future(future_converted, result)
    io_loop = IOLoop.current()

    def error_callback(future: Future) -> None:
        try:
            future.result()
        except asyncio.CancelledError:
            pass
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                app_log.error(
                    "Exception in Future %r after timeout", future, exc_info=True
                )

    def timeout_callback() -> None:
        if not result.done():
            result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future_add_done_callback(future_converted, error_callback)

    timeout_handle = io_loop.add_timeout(timeout, timeout_callback)
    if isinstance(future_converted, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future_add_done_callback(
            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)
        )
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(
            future_converted, lambda future: io_loop.remove_timeout(timeout_handle)
        )
    return result


def sleep(duration: float) -> "Future[None]":
    """Return a `.Future` that resolves after the given number of seconds.

    When used with ``yield`` in a coroutine, this is a non-blocking
    analogue to `time.sleep` (which should not be used in coroutines
    because it is blocking)::

        yield gen.sleep(0.5)

    Note that calling this function on its own does nothing; you must
    wait on the `.Future` it returns (usually by yielding it).

    .. versionadded:: 4.1
    """
    f = _create_future()
    IOLoop.current().call_later(
        duration, lambda: future_set_result_unless_cancelled(f, None)
    )
    return f


class _NullFuture(object):
    """_NullFuture resembles a Future that finished with a result of None.

    It's not actually a `Future` to avoid depending on a particular event loop.
    Handled as a special case in the coroutine runner.

    We lie and tell the type checker that a _NullFuture is a Future so
    we don't have to leak _NullFuture into lots of public APIs. But
    this means that the type checker can't warn us when we're passing
    a _NullFuture into a code path that doesn't understand what to do
    with it.
    """

    def result(self) -> None:
        return None

    def done(self) -> bool:
        return True


# _null_future is used as a dummy value in the coroutine runner. It differs
# from moment in that moment always adds a delay of one IOLoop iteration
# while _null_future is processed as soon as possible.
_null_future = typing.cast(Future, _NullFuture())

moment = typing.cast(Future, _NullFuture())
moment.__doc__ = """A special object which may be yielded to allow the IOLoop to run for
one iteration.

This is not needed in normal use but it can be helpful in long-running
coroutines that are likely to yield Futures that are ready instantly.

Usage: ``yield gen.moment``

In native coroutines, the equivalent of ``yield gen.moment`` is
``await asyncio.sleep(0)``.

.. versionadded:: 4.0

.. deprecated:: 4.5
   ``yield None`` (or ``yield`` with no argument) is now equivalent to
    ``yield gen.moment``.
"""


class Runner(object):
    """Internal implementation of `tornado.gen.coroutine`.

    Maintains information about pending callbacks and their results.

    The results of the generator are stored in ``result_future`` (a
    `.Future`)
    """

    def __init__(
        self,
        ctx_run: Callable,
        gen: "Generator[_Yieldable, Any, _T]",
        result_future: "Future[_T]",
        first_yielded: _Yieldable,
    ) -> None:
        self.ctx_run = ctx_run
        self.gen = gen
        self.result_future = result_future
        self.future = _null_future  # type: Union[None, Future]
        self.running = False
        self.finished = False
        self.io_loop = IOLoop.current()
        if self.handle_yield(first_yielded):
            gen = result_future = first_yielded = None  # type: ignore
            self.ctx_run(self.run)

    def run(self) -> None:
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if future is None:
                    raise Exception("No pending future")
                if not future.done():
                    return
                self.future = None
                try:
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        exc_info = sys.exc_info()
                    future = None

                    if exc_info is not None:
                        try:
                            yielded = self.gen.throw(*exc_info)  # type: ignore
                        finally:
                            # Break up a reference to itself
                            # for faster GC on CPython.
                            exc_info = None
                    else:
                        yielded = self.gen.send(value)

                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    future_set_result_unless_cancelled(
                        self.result_future, _value_from_stopiteration(e)
                    )
                    self.result_future = None  # type: ignore
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    future_set_exc_info(self.result_future, sys.exc_info())
                    self.result_future = None  # type: ignore
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False

    def handle_yield(self, yielded: _Yieldable) -> bool:
        try:
            self.future = convert_yielded(yielded)
        except BadYieldError:
            self.future = Future()
            future_set_exc_info(self.future, sys.exc_info())

        if self.future is moment:
            self.io_loop.add_callback(self.ctx_run, self.run)
            return False
        elif self.future is None:
            raise Exception("no pending future")
        elif not self.future.done():

            def inner(f: Any) -> None:
                # Break a reference cycle to speed GC.
                f = None  # noqa: F841
                self.ctx_run(self.run)

            self.io_loop.add_future(self.future, inner)
            return False
        return True

    def handle_exception(
        self, typ: Type[Exception], value: Exception, tb: types.TracebackType
    ) -> bool:
        if not self.running and not self.finished:
            self.future = Future()
            future_set_exc_info(self.future, (typ, value, tb))
            self.ctx_run(self.run)
            return True
        else:
            return False


# Convert Awaitables into Futures.
try:
    _wrap_awaitable = asyncio.ensure_future
except AttributeError:
    # asyncio.ensure_future was introduced in Python 3.4.4, but
    # Debian jessie still ships with 3.4.2 so try the old name.
    _wrap_awaitable = getattr(asyncio, "async")


def convert_yielded(yielded: _Yieldable) -> Future:
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and
    Futures. This has the side effect of starting any coroutines that
    did not start themselves, similar to `asyncio.ensure_future`.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1

    """
    if yielded is None or yielded is moment:
        return moment
    elif yielded is _null_future:
        return _null_future
    elif isinstance(yielded, (list, dict)):
        return multi(yielded)  # type: ignore
    elif is_future(yielded):
        return typing.cast(Future, yielded)
    elif isawaitable(yielded):
        return _wrap_awaitable(yielded)  # type: ignore
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,))


convert_yielded = singledispatch(convert_yielded)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user