{
    "file_diffs": [
        {
            "old_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\n``Futures`` are a pattern for concurrent programming introduced in\nPython 3.2 in the `concurrent.futures` package, and also adopted (in a\nslightly different form) in Python 3.4's `asyncio` package. This\npackage defines a ``Future`` class that is an alias for `asyncio.Future`\nwhen available, and a compatible implementation for older versions of\nPython. It also includes some utility functions for interacting with\n``Future`` objects.\n\nWhile this package is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport functools\nimport platform\nimport textwrap\nimport traceback\nimport sys\n\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer, is_finalizing\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import typing\nexcept ImportError:\n    typing = None\n\n\n# Can the garbage collector handle cycles that include __del__ methods?\n# This is true in cpython beginning with version 3.4 (PEP 442).\n_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and\n                        sys.version_info >= (3, 4))\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n# This class and associated code in the future object is derived\n# from the Trollius project, a backport of asyncio to Python 2.x - 3.x\n\n\nclass _TracebackLogger(object):\n    \"\"\"Helper to log a traceback upon destruction if not cleared.\n\n    This solves a nasty problem with Futures and Tasks that have an\n    exception set: if nobody asks for the exception, the exception is\n    never logged.  This violates the Zen of Python: 'Errors should\n    never pass silently.  Unless explicitly silenced.'\n\n    However, we don't want to log the exception as soon as\n    set_exception() is called: if the calling code is written\n    properly, it will get the exception and handle it properly.  But\n    we *do* want to log it if result() or exception() was never called\n    -- otherwise developers waste a lot of time wondering why their\n    buggy code fails silently.\n\n    An earlier attempt added a __del__() method to the Future class\n    itself, but this backfired because the presence of __del__()\n    prevents garbage collection from breaking cycles.  A way out of\n    this catch-22 is to avoid having a __del__() method on the Future\n    class itself, but instead to have a reference to a helper object\n    with a __del__() method that logs the traceback, where we ensure\n    that the helper object doesn't participate in cycles, and only the\n    Future has a reference to it.\n\n    The helper object is added when set_exception() is called.  When\n    the Future is collected, and the helper is present, the helper\n    object is also collected, and its __del__() method will log the\n    traceback.  When the Future's result() or exception() method is\n    called (and a helper object is present), it removes the the helper\n    object, after calling its clear() method to prevent it from\n    logging.\n\n    One downside is that we do a fair amount of work to extract the\n    traceback from the exception, even when it is never logged.  It\n    would seem cheaper to just store the exception object, but that\n    references the traceback, which references stack frames, which may\n    reference the Future, which references the _TracebackLogger, and\n    then the _TracebackLogger would be included in a cycle, which is\n    what we're trying to avoid!  As an optimization, we don't\n    immediately format the exception; we only do the work when\n    activate() is called, which call is delayed until after all the\n    Future's callbacks have run.  Since usually a Future has at least\n    one callback (typically set by 'yield From') and usually that\n    callback extracts the callback, thereby removing the need to\n    format the exception.\n\n    PS. I don't claim credit for this solution.  I first heard of it\n    in a discussion about closing files when they are collected.\n    \"\"\"\n\n    __slots__ = ('exc_info', 'formatted_tb')\n\n    def __init__(self, exc_info):\n        self.exc_info = exc_info\n        self.formatted_tb = None\n\n    def activate(self):\n        exc_info = self.exc_info\n        if exc_info is not None:\n            self.exc_info = None\n            self.formatted_tb = traceback.format_exception(*exc_info)\n\n    def clear(self):\n        self.exc_info = None\n        self.formatted_tb = None\n\n    def __del__(self, is_finalizing=is_finalizing):\n        if not is_finalizing() and self.formatted_tb:\n            app_log.error('Future exception was never retrieved: %s',\n                          ''.join(self.formatted_tb).rstrip())\n\n\nclass Future(object):\n    \"\"\"Placeholder for an asynchronous result.\n\n    A ``Future`` encapsulates the result of an asynchronous\n    operation.  In synchronous applications ``Futures`` are used\n    to wait for the result from a thread or process pool; in\n    Tornado they are normally used with `.IOLoop.add_future` or by\n    yielding them in a `.gen.coroutine`.\n\n    `tornado.concurrent.Future` is an alias for `asyncio.Future` when\n    that package is available (Python 3.4+). Unlike\n    `concurrent.futures.Future`, the ``Futures`` used by Tornado and\n    `asyncio` are not thread-safe (and therefore faster for use with\n    single-threaded event loops).\n\n    In addition to ``exception`` and ``set_exception``, Tornado's\n    ``Future`` implementation supports storing an ``exc_info`` triple\n    to support better tracebacks on Python 2. To set an ``exc_info``\n    triple, use `future_set_exc_info`, and to retrieve one, call\n    `result()` (which will raise it).\n\n    .. versionchanged:: 4.0\n       `tornado.concurrent.Future` is always a thread-unsafe ``Future``\n       with support for the ``exc_info`` methods.  Previously it would\n       be an alias for the thread-safe `concurrent.futures.Future`\n       if that package was available and fall back to the thread-unsafe\n       implementation if it was not.\n\n    .. versionchanged:: 4.1\n       If a `.Future` contains an error but that error is never observed\n       (by calling ``result()``, ``exception()``, or ``exc_info()``),\n       a stack trace will be logged when the `.Future` is garbage collected.\n       This normally indicates an error in the application, but in cases\n       where it results in undesired logging it may be necessary to\n       suppress the logging by ensuring that the exception is observed:\n       ``f.add_done_callback(lambda f: f.exception())``.\n\n    .. versionchanged:: 5.0\n\n       This class was previoiusly available under the name\n       ``TracebackFuture``. This name, which was deprecated since\n       version 4.0, has been removed. When `asyncio` is available\n       ``tornado.concurrent.Future`` is now an alias for\n       `asyncio.Future`. Like `asyncio.Future`, callbacks are now\n       always scheduled on the `.IOLoop` and are never run\n       synchronously.\n\n    \"\"\"\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exc_info = None\n\n        self._log_traceback = False   # Used for Python >= 3.4\n        self._tb_logger = None        # Used for Python <= 3.3\n\n        self._callbacks = []\n\n    # Implement the Python 3.5 Awaitable protocol if possible\n    # (we can't use return and yield together until py33).\n    if sys.version_info >= (3, 3):\n        exec(textwrap.dedent(\"\"\"\n        def __await__(self):\n            return (yield self)\n        \"\"\"))\n    else:\n        # Py2-compatible version for use with cython.\n        def __await__(self):\n            result = yield self\n            # StopIteration doesn't take args before py33,\n            # but Cython recognizes the args tuple.\n            e = StopIteration()\n            e.args = (result,)\n            raise e\n\n    def cancel(self):\n        \"\"\"Cancel the operation, if possible.\n\n        Tornado ``Futures`` do not support cancellation, so this method always\n        returns False.\n        \"\"\"\n        return False\n\n    def cancelled(self):\n        \"\"\"Returns True if the operation has been cancelled.\n\n        Tornado ``Futures`` do not support cancellation, so this method\n        always returns False.\n        \"\"\"\n        return False\n\n    def running(self):\n        \"\"\"Returns True if this operation is currently running.\"\"\"\n        return not self._done\n\n    def done(self):\n        \"\"\"Returns True if the future has finished running.\"\"\"\n        return self._done\n\n    def _clear_tb_log(self):\n        self._log_traceback = False\n        if self._tb_logger is not None:\n            self._tb_logger.clear()\n            self._tb_logger = None\n\n    def result(self, timeout=None):\n        \"\"\"If the operation succeeded, return its result.  If it failed,\n        re-raise its exception.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._result is not None:\n            return self._result\n        if self._exc_info is not None:\n            try:\n                raise_exc_info(self._exc_info)\n            finally:\n                self = None\n        self._check_done()\n        return self._result\n\n    def exception(self, timeout=None):\n        \"\"\"If the operation raised an exception, return the `Exception`\n        object.  Otherwise returns None.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._exc_info is not None:\n            return self._exc_info[1]\n        else:\n            self._check_done()\n            return None\n\n    def add_done_callback(self, fn):\n        \"\"\"Attaches the given callback to the `Future`.\n\n        It will be invoked with the `Future` as its argument when the Future\n        has finished running and its result is available.  In Tornado\n        consider using `.IOLoop.add_future` instead of calling\n        `add_done_callback` directly.\n        \"\"\"\n        if self._done:\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(fn, self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        \"\"\"Sets the result of a ``Future``.\n\n        It is undefined to call any of the ``set`` methods more than once\n        on the same object.\n        \"\"\"\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        \"\"\"Sets the exception of a ``Future.``\"\"\"\n        self.set_exc_info(\n            (exception.__class__,\n             exception,\n             getattr(exception, '__traceback__', None)))\n\n    def exc_info(self):\n        \"\"\"Returns a tuple in the same format as `sys.exc_info` or None.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._clear_tb_log()\n        return self._exc_info\n\n    def set_exc_info(self, exc_info):\n        \"\"\"Sets the exception information of a ``Future.``\n\n        Preserves tracebacks on Python 2.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._exc_info = exc_info\n        self._log_traceback = True\n        if not _GC_CYCLE_FINALIZERS:\n            self._tb_logger = _TracebackLogger(exc_info)\n\n        try:\n            self._set_done()\n        finally:\n            # Activate the logger after all callbacks have had a\n            # chance to call result() or exception().\n            if self._log_traceback and self._tb_logger is not None:\n                self._tb_logger.activate()\n        self._exc_info = exc_info\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        if self._callbacks:\n            from tornado.ioloop import IOLoop\n            loop = IOLoop.current()\n            for cb in self._callbacks:\n                loop.add_callback(cb, self)\n            self._callbacks = None\n\n    # On Python 3.3 or older, objects with a destructor part of a reference\n    # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to\n    # the PEP 442.\n    if _GC_CYCLE_FINALIZERS:\n        def __del__(self, is_finalizing=is_finalizing):\n            if is_finalizing() or not self._log_traceback:\n                # set_exception() was not called, or result() or exception()\n                # has consumed the exception\n                return\n\n            tb = traceback.format_exception(*self._exc_info)\n\n            app_log.error('Future %r exception was never retrieved: %s',\n                          self, ''.join(tb).rstrip())\n\n\nif asyncio is not None:\n    Future = asyncio.Future  # noqa\n\nif futures is None:\n    FUTURES = Future  # type: typing.Union[type, typing.Tuple[type, ...]]\nelse:\n    FUTURES = (futures.Future, Future)\n\n\ndef is_future(x):\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait=True):\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args, **kwargs):\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    The decorated method may be called with a ``callback`` keyword\n    argument and returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n    \"\"\"\n    def run_on_executor_decorator(fn):\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self, *args, **kwargs):\n            callback = kwargs.pop(\"callback\", None)\n            future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            if callback:\n                from tornado.ioloop import IOLoop\n                IOLoop.current().add_future(\n                    future, lambda future: callback(future.result()))\n            return future\n        return wrapper\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a\n    `Future`.\n\n    This decorator was provided to ease the transition from\n    callback-oriented code to coroutines. It is not recommended for\n    new code.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `.StackContext` and passed along to the ``Future``).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with ``Future.result()`` as an argument.  If the function fails, the\n    callback will not be run and an exception will be raised into the\n    surrounding `.StackContext`.\n\n    If no callback is given, the caller should use the ``Future`` to\n    wait for the function to complete (perhaps by yielding it in a\n    `.gen.engine` function, or passing it to `.IOLoop.add_future`).\n\n    Usage:\n\n    .. testcode::\n\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    ..\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(\n            lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value),\n            args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future_set_exc_info(future, (typ, value, tb))\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            future.result()\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                result = future.result()\n                if result is _NO_RESULT:\n                    callback()\n                else:\n                    callback(future.result())\n            future_add_done_callback(future, wrap(run_callback))\n        return future\n    return wrapper\n\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if b.done():\n            return\n        if (hasattr(a, 'exc_info') and\n                a.exc_info() is not None):\n            future_set_exc_info(b, a.exc_info())\n        elif a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(future, value):\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids asyncio.InvalidStateError when calling set_result() on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exc_info(future, exc_info):\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and Tornado's extensions to\n    enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if hasattr(future, 'set_exc_info'):\n        # Tornado's Future\n        future.set_exc_info(exc_info)\n    else:\n        # asyncio.Future\n        future.set_exception(exc_info[1])\n\n\ndef future_add_done_callback(future, callback):\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\n",
            "new_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\n``Futures`` are a pattern for concurrent programming introduced in\nPython 3.2 in the `concurrent.futures` package, and also adopted (in a\nslightly different form) in Python 3.4's `asyncio` package. This\npackage defines a ``Future`` class that is an alias for `asyncio.Future`\nwhen available, and a compatible implementation for older versions of\nPython. It also includes some utility functions for interacting with\n``Future`` objects.\n\nWhile this package is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport functools\nimport platform\nimport textwrap\nimport traceback\nimport sys\n\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer, is_finalizing\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import typing\nexcept ImportError:\n    typing = None\n\n\n# Can the garbage collector handle cycles that include __del__ methods?\n# This is true in cpython beginning with version 3.4 (PEP 442).\n_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and\n                        sys.version_info >= (3, 4))\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n# This class and associated code in the future object is derived\n# from the Trollius project, a backport of asyncio to Python 2.x - 3.x\n\n\nclass _TracebackLogger(object):\n    \"\"\"Helper to log a traceback upon destruction if not cleared.\n\n    This solves a nasty problem with Futures and Tasks that have an\n    exception set: if nobody asks for the exception, the exception is\n    never logged.  This violates the Zen of Python: 'Errors should\n    never pass silently.  Unless explicitly silenced.'\n\n    However, we don't want to log the exception as soon as\n    set_exception() is called: if the calling code is written\n    properly, it will get the exception and handle it properly.  But\n    we *do* want to log it if result() or exception() was never called\n    -- otherwise developers waste a lot of time wondering why their\n    buggy code fails silently.\n\n    An earlier attempt added a __del__() method to the Future class\n    itself, but this backfired because the presence of __del__()\n    prevents garbage collection from breaking cycles.  A way out of\n    this catch-22 is to avoid having a __del__() method on the Future\n    class itself, but instead to have a reference to a helper object\n    with a __del__() method that logs the traceback, where we ensure\n    that the helper object doesn't participate in cycles, and only the\n    Future has a reference to it.\n\n    The helper object is added when set_exception() is called.  When\n    the Future is collected, and the helper is present, the helper\n    object is also collected, and its __del__() method will log the\n    traceback.  When the Future's result() or exception() method is\n    called (and a helper object is present), it removes the the helper\n    object, after calling its clear() method to prevent it from\n    logging.\n\n    One downside is that we do a fair amount of work to extract the\n    traceback from the exception, even when it is never logged.  It\n    would seem cheaper to just store the exception object, but that\n    references the traceback, which references stack frames, which may\n    reference the Future, which references the _TracebackLogger, and\n    then the _TracebackLogger would be included in a cycle, which is\n    what we're trying to avoid!  As an optimization, we don't\n    immediately format the exception; we only do the work when\n    activate() is called, which call is delayed until after all the\n    Future's callbacks have run.  Since usually a Future has at least\n    one callback (typically set by 'yield From') and usually that\n    callback extracts the callback, thereby removing the need to\n    format the exception.\n\n    PS. I don't claim credit for this solution.  I first heard of it\n    in a discussion about closing files when they are collected.\n    \"\"\"\n\n    __slots__ = ('exc_info', 'formatted_tb')\n\n    def __init__(self, exc_info):\n        self.exc_info = exc_info\n        self.formatted_tb = None\n\n    def activate(self):\n        exc_info = self.exc_info\n        if exc_info is not None:\n            self.exc_info = None\n            self.formatted_tb = traceback.format_exception(*exc_info)\n\n    def clear(self):\n        self.exc_info = None\n        self.formatted_tb = None\n\n    def __del__(self, is_finalizing=is_finalizing):\n        if not is_finalizing() and self.formatted_tb:\n            app_log.error('Future exception was never retrieved: %s',\n                          ''.join(self.formatted_tb).rstrip())\n\n\nclass Future(object):\n    \"\"\"Placeholder for an asynchronous result.\n\n    A ``Future`` encapsulates the result of an asynchronous\n    operation.  In synchronous applications ``Futures`` are used\n    to wait for the result from a thread or process pool; in\n    Tornado they are normally used with `.IOLoop.add_future` or by\n    yielding them in a `.gen.coroutine`.\n\n    `tornado.concurrent.Future` is an alias for `asyncio.Future` when\n    that package is available (Python 3.4+). Unlike\n    `concurrent.futures.Future`, the ``Futures`` used by Tornado and\n    `asyncio` are not thread-safe (and therefore faster for use with\n    single-threaded event loops).\n\n    In addition to ``exception`` and ``set_exception``, Tornado's\n    ``Future`` implementation supports storing an ``exc_info`` triple\n    to support better tracebacks on Python 2. To set an ``exc_info``\n    triple, use `future_set_exc_info`, and to retrieve one, call\n    `result()` (which will raise it).\n\n    .. versionchanged:: 4.0\n       `tornado.concurrent.Future` is always a thread-unsafe ``Future``\n       with support for the ``exc_info`` methods.  Previously it would\n       be an alias for the thread-safe `concurrent.futures.Future`\n       if that package was available and fall back to the thread-unsafe\n       implementation if it was not.\n\n    .. versionchanged:: 4.1\n       If a `.Future` contains an error but that error is never observed\n       (by calling ``result()``, ``exception()``, or ``exc_info()``),\n       a stack trace will be logged when the `.Future` is garbage collected.\n       This normally indicates an error in the application, but in cases\n       where it results in undesired logging it may be necessary to\n       suppress the logging by ensuring that the exception is observed:\n       ``f.add_done_callback(lambda f: f.exception())``.\n\n    .. versionchanged:: 5.0\n\n       This class was previoiusly available under the name\n       ``TracebackFuture``. This name, which was deprecated since\n       version 4.0, has been removed. When `asyncio` is available\n       ``tornado.concurrent.Future`` is now an alias for\n       `asyncio.Future`. Like `asyncio.Future`, callbacks are now\n       always scheduled on the `.IOLoop` and are never run\n       synchronously.\n\n    \"\"\"\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exc_info = None\n\n        self._log_traceback = False   # Used for Python >= 3.4\n        self._tb_logger = None        # Used for Python <= 3.3\n\n        self._callbacks = []\n\n    # Implement the Python 3.5 Awaitable protocol if possible\n    # (we can't use return and yield together until py33).\n    if sys.version_info >= (3, 3):\n        exec(textwrap.dedent(\"\"\"\n        def __await__(self):\n            return (yield self)\n        \"\"\"))\n    else:\n        # Py2-compatible version for use with cython.\n        def __await__(self):\n            result = yield self\n            # StopIteration doesn't take args before py33,\n            # but Cython recognizes the args tuple.\n            e = StopIteration()\n            e.args = (result,)\n            raise e\n\n    def cancel(self):\n        \"\"\"Cancel the operation, if possible.\n\n        Tornado ``Futures`` do not support cancellation, so this method always\n        returns False.\n        \"\"\"\n        return False\n\n    def cancelled(self):\n        \"\"\"Returns True if the operation has been cancelled.\n\n        Tornado ``Futures`` do not support cancellation, so this method\n        always returns False.\n        \"\"\"\n        return False\n\n    def running(self):\n        \"\"\"Returns True if this operation is currently running.\"\"\"\n        return not self._done\n\n    def done(self):\n        \"\"\"Returns True if the future has finished running.\"\"\"\n        return self._done\n\n    def _clear_tb_log(self):\n        self._log_traceback = False\n        if self._tb_logger is not None:\n            self._tb_logger.clear()\n            self._tb_logger = None\n\n    def result(self, timeout=None):\n        \"\"\"If the operation succeeded, return its result.  If it failed,\n        re-raise its exception.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._result is not None:\n            return self._result\n        if self._exc_info is not None:\n            try:\n                raise_exc_info(self._exc_info)\n            finally:\n                self = None\n        self._check_done()\n        return self._result\n\n    def exception(self, timeout=None):\n        \"\"\"If the operation raised an exception, return the `Exception`\n        object.  Otherwise returns None.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._exc_info is not None:\n            return self._exc_info[1]\n        else:\n            self._check_done()\n            return None\n\n    def add_done_callback(self, fn):\n        \"\"\"Attaches the given callback to the `Future`.\n\n        It will be invoked with the `Future` as its argument when the Future\n        has finished running and its result is available.  In Tornado\n        consider using `.IOLoop.add_future` instead of calling\n        `add_done_callback` directly.\n        \"\"\"\n        if self._done:\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(fn, self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        \"\"\"Sets the result of a ``Future``.\n\n        It is undefined to call any of the ``set`` methods more than once\n        on the same object.\n        \"\"\"\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        \"\"\"Sets the exception of a ``Future.``\"\"\"\n        self.set_exc_info(\n            (exception.__class__,\n             exception,\n             getattr(exception, '__traceback__', None)))\n\n    def exc_info(self):\n        \"\"\"Returns a tuple in the same format as `sys.exc_info` or None.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._clear_tb_log()\n        return self._exc_info\n\n    def set_exc_info(self, exc_info):\n        \"\"\"Sets the exception information of a ``Future.``\n\n        Preserves tracebacks on Python 2.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._exc_info = exc_info\n        self._log_traceback = True\n        if not _GC_CYCLE_FINALIZERS:\n            self._tb_logger = _TracebackLogger(exc_info)\n\n        try:\n            self._set_done()\n        finally:\n            # Activate the logger after all callbacks have had a\n            # chance to call result() or exception().\n            if self._log_traceback and self._tb_logger is not None:\n                self._tb_logger.activate()\n        self._exc_info = exc_info\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        if self._callbacks:\n            from tornado.ioloop import IOLoop\n            loop = IOLoop.current()\n            for cb in self._callbacks:\n                loop.add_callback(cb, self)\n            self._callbacks = None\n\n    # On Python 3.3 or older, objects with a destructor part of a reference\n    # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to\n    # the PEP 442.\n    if _GC_CYCLE_FINALIZERS:\n        def __del__(self, is_finalizing=is_finalizing):\n            if is_finalizing() or not self._log_traceback:\n                # set_exception() was not called, or result() or exception()\n                # has consumed the exception\n                return\n\n            tb = traceback.format_exception(*self._exc_info)\n\n            app_log.error('Future %r exception was never retrieved: %s',\n                          self, ''.join(tb).rstrip())\n\n\nif asyncio is not None:\n    Future = asyncio.Future  # noqa\n\nif futures is None:\n    FUTURES = Future  # type: typing.Union[type, typing.Tuple[type, ...]]\nelse:\n    FUTURES = (futures.Future, Future)\n\n\ndef is_future(x):\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait=True):\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args, **kwargs):\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    The decorated method may be called with a ``callback`` keyword\n    argument and returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n\n    .. versionchanged:: 5.1\n       Returns a `.Future` compatible with ``await`` instead of a\n       `concurrent.futures.Future`.\n    \"\"\"\n    def run_on_executor_decorator(fn):\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self, *args, **kwargs):\n            callback = kwargs.pop(\"callback\", None)\n            async_future = Future()\n            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            chain_future(conc_future, async_future)\n            if callback:\n                from tornado.ioloop import IOLoop\n                IOLoop.current().add_future(\n                    async_future, lambda future: callback(future.result()))\n            return async_future\n        return wrapper\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a\n    `Future`.\n\n    This decorator was provided to ease the transition from\n    callback-oriented code to coroutines. It is not recommended for\n    new code.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `.StackContext` and passed along to the ``Future``).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with ``Future.result()`` as an argument.  If the function fails, the\n    callback will not be run and an exception will be raised into the\n    surrounding `.StackContext`.\n\n    If no callback is given, the caller should use the ``Future`` to\n    wait for the function to complete (perhaps by yielding it in a\n    `.gen.engine` function, or passing it to `.IOLoop.add_future`).\n\n    Usage:\n\n    .. testcode::\n\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    ..\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(\n            lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value),\n            args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future_set_exc_info(future, (typ, value, tb))\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            future.result()\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                result = future.result()\n                if result is _NO_RESULT:\n                    callback()\n                else:\n                    callback(future.result())\n            future_add_done_callback(future, wrap(run_callback))\n        return future\n    return wrapper\n\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if b.done():\n            return\n        if (hasattr(a, 'exc_info') and\n                a.exc_info() is not None):\n            future_set_exc_info(b, a.exc_info())\n        elif a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(future, value):\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids asyncio.InvalidStateError when calling set_result() on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exc_info(future, exc_info):\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and Tornado's extensions to\n    enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if hasattr(future, 'set_exc_info'):\n        # Tornado's Future\n        future.set_exc_info(exc_info)\n    else:\n        # asyncio.Future\n        future.set_exception(exc_info[1])\n\n\ndef future_add_done_callback(future, callback):\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\n",
            "header": {
                "file": {
                    "path": "tornado/concurrent.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1a79f1e1",
                "new_commit_hash": "aa38bb99",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/concurrent.py"
            },
            "plus_file": {
                "path": "b/tornado/concurrent.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 421,
                            "length": 6
                        },
                        "new_range": {
                            "start": 421,
                            "length": 10
                        },
                        "section": "def run_on_executor(*args, **kwargs):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    .. versionchanged:: 5.0",
                                "type": "context"
                            },
                            {
                                "content": "       Always uses the current IOLoop instead of ``self.io_loop``.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    .. versionchanged:: 5.1",
                                "type": "added"
                            },
                            {
                                "content": "       Returns a `.Future` compatible with ``await`` instead of a",
                                "type": "added"
                            },
                            {
                                "content": "       `concurrent.futures.Future`.",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    def run_on_executor_decorator(fn):",
                                "type": "context"
                            },
                            {
                                "content": "        executor = kwargs.get(\"executor\", \"executor\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/concurrent.py",
                            "type": "function",
                            "name": "run_on_executor",
                            "content": "def run_on_executor(*args, **kwargs):\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    The decorated method may be called with a ``callback`` keyword\n    argument and returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n\n    .. versionchanged:: 5.1\n       Returns a `.Future` compatible with ``await`` instead of a\n       `concurrent.futures.Future`.\n    \"\"\"\n    def run_on_executor_decorator(fn):\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self, *args, **kwargs):\n            callback = kwargs.pop(\"callback\", None)\n            async_future = Future()\n            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            chain_future(conc_future, async_future)\n            if callback:\n                from tornado.ioloop import IOLoop\n                IOLoop.current().add_future(\n                    async_future, lambda future: callback(future.result()))\n            return async_future\n        return wrapper\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 398,
                            "end_lineno": 450,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 428,
                            "length": 12
                        },
                        "new_range": {
                            "start": 432,
                            "length": 14
                        },
                        "section": "def run_on_executor(*args, **kwargs):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        @functools.wraps(fn)",
                                "type": "context"
                            },
                            {
                                "content": "        def wrapper(self, *args, **kwargs):",
                                "type": "context"
                            },
                            {
                                "content": "            callback = kwargs.pop(\"callback\", None)",
                                "type": "context"
                            },
                            {
                                "content": "            future = getattr(self, executor).submit(fn, self, *args, **kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "            async_future = Future()",
                                "type": "added"
                            },
                            {
                                "content": "            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "            chain_future(conc_future, async_future)",
                                "type": "added"
                            },
                            {
                                "content": "            if callback:",
                                "type": "context"
                            },
                            {
                                "content": "                from tornado.ioloop import IOLoop",
                                "type": "context"
                            },
                            {
                                "content": "                IOLoop.current().add_future(",
                                "type": "context"
                            },
                            {
                                "content": "                    future, lambda future: callback(future.result()))",
                                "type": "deleted"
                            },
                            {
                                "content": "            return future",
                                "type": "deleted"
                            },
                            {
                                "content": "                    async_future, lambda future: callback(future.result()))",
                                "type": "added"
                            },
                            {
                                "content": "            return async_future",
                                "type": "added"
                            },
                            {
                                "content": "        return wrapper",
                                "type": "context"
                            },
                            {
                                "content": "    if args and kwargs:",
                                "type": "context"
                            },
                            {
                                "content": "        raise ValueError(\"cannot combine positional and keyword args\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/concurrent.py",
                            "type": "function",
                            "name": "run_on_executor",
                            "content": "def run_on_executor(*args, **kwargs):\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    The decorated method may be called with a ``callback`` keyword\n    argument and returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n    \"\"\"\n    def run_on_executor_decorator(fn):\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self, *args, **kwargs):\n            callback = kwargs.pop(\"callback\", None)\n            future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            if callback:\n                from tornado.ioloop import IOLoop\n                IOLoop.current().add_future(\n                    future, lambda future: callback(future.result()))\n            return future\n        return wrapper\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 398,
                            "end_lineno": 444,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function\n\nimport gc\nimport logging\nimport re\nimport socket\nimport sys\nimport traceback\n\nfrom tornado.concurrent import (Future, return_future, ReturnValueIgnoredError,\n                                run_on_executor, future_set_result_unless_cancelled)\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\nfrom tornado.test.util import unittest\n\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\n\nclass MiscFutureTest(AsyncTestCase):\n\n    def test_future_set_result_unless_cancelled(self):\n        fut = Future()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.result(), 42)\n        self.assertFalse(fut.cancelled())\n\n        fut = Future()\n        fut.cancel()\n        is_cancelled = fut.cancelled()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.cancelled(), is_cancelled)\n        if not is_cancelled:\n            self.assertEqual(fut.result(), 42)\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        future = self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n        # result of this future is undefined, but not an error\n        future.result()\n\n    def test_no_result_future_callback(self):\n        future = self.no_result_future(callback=lambda: self.stop())\n        result = self.wait()\n        self.assertIs(result, None)\n        future.result()\n\n    @gen_test\n    def test_future_traceback(self):\n        @return_future\n        @gen.engine\n        def f(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            try:\n                1 / 0\n            except ZeroDivisionError:\n                self.expected_frame = traceback.extract_tb(\n                    sys.exc_info()[2], limit=1)[0]\n                raise\n        try:\n            yield f()\n            self.fail(\"didn't get expected exception\")\n        except ZeroDivisionError:\n            tb = traceback.extract_tb(sys.exc_info()[2])\n            self.assertIn(self.expected_frame, tb)\n\n    @gen_test\n    def test_uncaught_exception_log(self):\n        if IOLoop.configured_class().__name__.endswith('AsyncIOLoop'):\n            # Install an exception handler that mirrors our\n            # non-asyncio logging behavior.\n            def exc_handler(loop, context):\n                app_log.error('%s: %s', context['message'],\n                              type(context.get('exception')))\n            self.io_loop.asyncio_loop.set_exception_handler(exc_handler)\n\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        g = f()\n\n        with ExpectLog(app_log,\n                       \"(?s)Future.* exception was never retrieved:\"\n                       \".*ZeroDivisionError\"):\n            yield gen.moment\n            yield gen.moment\n            # For some reason, TwistedIOLoop and pypy3 need a third iteration\n            # in order to drain references to the future\n            yield gen.moment\n            del g\n            gc.collect()  # for PyPy\n\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\n\n\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.debug(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port):\n        self.port = port\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.debug('capitalize')\n        stream = IOStream(socket.socket())\n        logging.debug('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.debug('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.debug('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()  # type: ignore\n        self.server = CapServer()\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()  # type: ignore\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = GeneratorCapClient\n\n\n@unittest.skipIf(futures is None, \"concurrent.futures module not present\")\nclass RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function\n\nimport gc\nimport logging\nimport re\nimport socket\nimport sys\nimport traceback\n\nfrom tornado.concurrent import (Future, return_future, ReturnValueIgnoredError,\n                                run_on_executor, future_set_result_unless_cancelled)\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\nfrom tornado.test.util import unittest, skipBefore35, exec_test\n\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\n\nclass MiscFutureTest(AsyncTestCase):\n\n    def test_future_set_result_unless_cancelled(self):\n        fut = Future()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.result(), 42)\n        self.assertFalse(fut.cancelled())\n\n        fut = Future()\n        fut.cancel()\n        is_cancelled = fut.cancelled()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.cancelled(), is_cancelled)\n        if not is_cancelled:\n            self.assertEqual(fut.result(), 42)\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        future = self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n        # result of this future is undefined, but not an error\n        future.result()\n\n    def test_no_result_future_callback(self):\n        future = self.no_result_future(callback=lambda: self.stop())\n        result = self.wait()\n        self.assertIs(result, None)\n        future.result()\n\n    @gen_test\n    def test_future_traceback(self):\n        @return_future\n        @gen.engine\n        def f(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            try:\n                1 / 0\n            except ZeroDivisionError:\n                self.expected_frame = traceback.extract_tb(\n                    sys.exc_info()[2], limit=1)[0]\n                raise\n        try:\n            yield f()\n            self.fail(\"didn't get expected exception\")\n        except ZeroDivisionError:\n            tb = traceback.extract_tb(sys.exc_info()[2])\n            self.assertIn(self.expected_frame, tb)\n\n    @gen_test\n    def test_uncaught_exception_log(self):\n        if IOLoop.configured_class().__name__.endswith('AsyncIOLoop'):\n            # Install an exception handler that mirrors our\n            # non-asyncio logging behavior.\n            def exc_handler(loop, context):\n                app_log.error('%s: %s', context['message'],\n                              type(context.get('exception')))\n            self.io_loop.asyncio_loop.set_exception_handler(exc_handler)\n\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        g = f()\n\n        with ExpectLog(app_log,\n                       \"(?s)Future.* exception was never retrieved:\"\n                       \".*ZeroDivisionError\"):\n            yield gen.moment\n            yield gen.moment\n            # For some reason, TwistedIOLoop and pypy3 need a third iteration\n            # in order to drain references to the future\n            yield gen.moment\n            del g\n            gc.collect()  # for PyPy\n\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\n\n\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.debug(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port):\n        self.port = port\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.debug('capitalize')\n        stream = IOStream(socket.socket())\n        logging.debug('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.debug('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.debug('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()  # type: ignore\n        self.server = CapServer()\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()  # type: ignore\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = GeneratorCapClient\n\n\n@unittest.skipIf(futures is None, \"concurrent.futures module not present\")\nclass RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @skipBefore35\n    @gen_test\n    def test_async_await(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f():\n            answer = await o.f()\n            return answer\n        \"\"\")\n        result = yield namespace['f']()\n        self.assertEqual(result, 42)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/concurrent_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1b6f8ee9",
                "new_commit_hash": "b00b80dd",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/concurrent_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/concurrent_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 31,
                            "length": 7
                        },
                        "new_range": {
                            "start": 31,
                            "length": 7
                        },
                        "section": "from tornado.log import app_log"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from tornado import stack_context",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.tcpserver import TCPServer",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.test.util import unittest",
                                "type": "deleted"
                            },
                            {
                                "content": "from tornado.test.util import unittest, skipBefore35, exec_test",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "try:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.test.util import unittest, skipBefore35, exec_test",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 34,
                            "end_lineno": 34,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.test.util import unittest",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 34,
                            "end_lineno": 34,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 429,
                            "length": 6
                        },
                        "new_range": {
                            "start": 429,
                            "length": 26
                        },
                        "section": "class RunOnExecutorTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        answer = yield o.f()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(answer, 42)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @skipBefore35",
                                "type": "added"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_async_await(self):",
                                "type": "added"
                            },
                            {
                                "content": "        class Object(object):",
                                "type": "added"
                            },
                            {
                                "content": "            def __init__(self):",
                                "type": "added"
                            },
                            {
                                "content": "                self.executor = futures.thread.ThreadPoolExecutor(1)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            @run_on_executor()",
                                "type": "added"
                            },
                            {
                                "content": "            def f(self):",
                                "type": "added"
                            },
                            {
                                "content": "                return 42",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        o = Object()",
                                "type": "added"
                            },
                            {
                                "content": "        namespace = exec_test(globals(), locals(), \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        async def f():",
                                "type": "added"
                            },
                            {
                                "content": "            answer = await o.f()",
                                "type": "added"
                            },
                            {
                                "content": "            return answer",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\")",
                                "type": "added"
                            },
                            {
                                "content": "        result = yield namespace['f']()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(result, 42)",
                                "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/concurrent_test.py",
                            "type": "class",
                            "name": "RunOnExecutorTest",
                            "content": "class RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @skipBefore35\n    @gen_test\n    def test_async_await(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f():\n            answer = await o.f()\n            return answer\n        \"\"\")\n        result = yield namespace['f']()\n        self.assertEqual(result, 42)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 389,
                            "end_lineno": 450,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/concurrent_test.py",
                            "type": "method",
                            "name": "RunOnExecutorTest.test_async_await",
                            "content": "class RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @skipBefore35\n    @gen_test\n    def test_async_await(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f():\n            answer = await o.f()\n            return answer\n        \"\"\")\n        result = yield namespace['f']()\n        self.assertEqual(result, 42)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 434,
                            "end_lineno": 450,
                            "parent": {
                                "file_name": "tornado/test/concurrent_test.py",
                                "type": "class",
                                "name": "RunOnExecutorTest",
                                "content": "class RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @skipBefore35\n    @gen_test\n    def test_async_await(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f():\n            answer = await o.f()\n            return answer\n        \"\"\")\n        result = yield namespace['f']()\n        self.assertEqual(result, 42)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 389,
                                "end_lineno": 450,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7^",
    "new_commit_hash": "e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7",
    "commit_message": "concurrent: run_on_executor returns async futures, not concurrent ones\n\nFixes #2276",
    "commit_date": "2018-03-11T18:09:05-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7",
    "test_file_codes": [
        "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function\n\nimport gc\nimport logging\nimport re\nimport socket\nimport sys\nimport traceback\n\nfrom tornado.concurrent import (Future, return_future, ReturnValueIgnoredError,\n                                run_on_executor, future_set_result_unless_cancelled)\nfrom tornado.escape import utf8, to_unicode\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\nfrom tornado.test.util import unittest, skipBefore35, exec_test\n\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\n\nclass MiscFutureTest(AsyncTestCase):\n\n    def test_future_set_result_unless_cancelled(self):\n        fut = Future()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.result(), 42)\n        self.assertFalse(fut.cancelled())\n\n        fut = Future()\n        fut.cancel()\n        is_cancelled = fut.cancelled()\n        future_set_result_unless_cancelled(fut, 42)\n        self.assertEqual(fut.cancelled(), is_cancelled)\n        if not is_cancelled:\n            self.assertEqual(fut.result(), 42)\n\n\nclass ReturnFutureTest(AsyncTestCase):\n    @return_future\n    def sync_future(self, callback):\n        callback(42)\n\n    @return_future\n    def async_future(self, callback):\n        self.io_loop.add_callback(callback, 42)\n\n    @return_future\n    def immediate_failure(self, callback):\n        1 / 0\n\n    @return_future\n    def delayed_failure(self, callback):\n        self.io_loop.add_callback(lambda: 1 / 0)\n\n    @return_future\n    def return_value(self, callback):\n        # Note that the result of both running the callback and returning\n        # a value (or raising an exception) is unspecified; with current\n        # implementations the last event prior to callback resolution wins.\n        return 42\n\n    @return_future\n    def no_result_future(self, callback):\n        callback()\n\n    def test_immediate_failure(self):\n        with self.assertRaises(ZeroDivisionError):\n            # The caller sees the error just like a normal function.\n            self.immediate_failure(callback=self.stop)\n        # The callback is not run because the function failed synchronously.\n        self.io_loop.add_timeout(self.io_loop.time() + 0.05, self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n\n    def test_return_value(self):\n        with self.assertRaises(ReturnValueIgnoredError):\n            self.return_value(callback=self.stop)\n\n    def test_callback_kw(self):\n        future = self.sync_future(callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_callback_positional(self):\n        # When the callback is passed in positionally, future_wrap shouldn't\n        # add another callback in the kwargs.\n        future = self.sync_future(self.stop)\n        result = self.wait()\n        self.assertEqual(result, 42)\n        self.assertEqual(future.result(), 42)\n\n    def test_no_callback(self):\n        future = self.sync_future()\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_kw(self):\n        # explicitly pass None as callback\n        future = self.sync_future(callback=None)\n        self.assertEqual(future.result(), 42)\n\n    def test_none_callback_pos(self):\n        future = self.sync_future(None)\n        self.assertEqual(future.result(), 42)\n\n    def test_async_future(self):\n        future = self.async_future()\n        self.assertFalse(future.done())\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        self.assertEqual(future.result(), 42)\n\n    @gen_test\n    def test_async_future_gen(self):\n        result = yield self.async_future()\n        self.assertEqual(result, 42)\n\n    def test_delayed_failure(self):\n        future = self.delayed_failure()\n        self.io_loop.add_future(future, self.stop)\n        future2 = self.wait()\n        self.assertIs(future, future2)\n        with self.assertRaises(ZeroDivisionError):\n            future.result()\n\n    def test_kw_only_callback(self):\n        @return_future\n        def f(**kwargs):\n            kwargs['callback'](42)\n        future = f()\n        self.assertEqual(future.result(), 42)\n\n    def test_error_in_callback(self):\n        self.sync_future(callback=lambda future: 1 / 0)\n        # The exception gets caught by our StackContext and will be re-raised\n        # when we wait.\n        self.assertRaises(ZeroDivisionError, self.wait)\n\n    def test_no_result_future(self):\n        future = self.no_result_future(self.stop)\n        result = self.wait()\n        self.assertIs(result, None)\n        # result of this future is undefined, but not an error\n        future.result()\n\n    def test_no_result_future_callback(self):\n        future = self.no_result_future(callback=lambda: self.stop())\n        result = self.wait()\n        self.assertIs(result, None)\n        future.result()\n\n    @gen_test\n    def test_future_traceback(self):\n        @return_future\n        @gen.engine\n        def f(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            try:\n                1 / 0\n            except ZeroDivisionError:\n                self.expected_frame = traceback.extract_tb(\n                    sys.exc_info()[2], limit=1)[0]\n                raise\n        try:\n            yield f()\n            self.fail(\"didn't get expected exception\")\n        except ZeroDivisionError:\n            tb = traceback.extract_tb(sys.exc_info()[2])\n            self.assertIn(self.expected_frame, tb)\n\n    @gen_test\n    def test_uncaught_exception_log(self):\n        if IOLoop.configured_class().__name__.endswith('AsyncIOLoop'):\n            # Install an exception handler that mirrors our\n            # non-asyncio logging behavior.\n            def exc_handler(loop, context):\n                app_log.error('%s: %s', context['message'],\n                              type(context.get('exception')))\n            self.io_loop.asyncio_loop.set_exception_handler(exc_handler)\n\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n\n        g = f()\n\n        with ExpectLog(app_log,\n                       \"(?s)Future.* exception was never retrieved:\"\n                       \".*ZeroDivisionError\"):\n            yield gen.moment\n            yield gen.moment\n            # For some reason, TwistedIOLoop and pypy3 need a third iteration\n            # in order to drain references to the future\n            yield gen.moment\n            del g\n            gc.collect()  # for PyPy\n\n\n# The following series of classes demonstrate and test various styles\n# of use, with and without generators and futures.\n\n\nclass CapServer(TCPServer):\n    def handle_stream(self, stream, address):\n        logging.debug(\"handle_stream\")\n        self.stream = stream\n        self.stream.read_until(b\"\\n\", self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        data = to_unicode(data)\n        if data == data.upper():\n            self.stream.write(b\"error\\talready capitalized\\n\")\n        else:\n            # data already has \\n\n            self.stream.write(utf8(\"ok\\t%s\" % data.upper()))\n        self.stream.close()\n\n\nclass CapError(Exception):\n    pass\n\n\nclass BaseCapClient(object):\n    def __init__(self, port):\n        self.port = port\n\n    def process_response(self, data):\n        status, message = re.match('(.*)\\t(.*)\\n', to_unicode(data)).groups()\n        if status == 'ok':\n            return message\n        else:\n            raise CapError(message)\n\n\nclass ManualCapClient(BaseCapClient):\n    def capitalize(self, request_data, callback=None):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.future = Future()\n        if callback is not None:\n            self.future.add_done_callback(\n                stack_context.wrap(lambda future: callback(future.result())))\n        return self.future\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        try:\n            self.future.set_result(self.process_response(data))\n        except CapError as e:\n            self.future.set_exception(e)\n\n\nclass DecoratorCapClient(BaseCapClient):\n    @return_future\n    def capitalize(self, request_data, callback):\n        logging.debug(\"capitalize\")\n        self.request_data = request_data\n        self.stream = IOStream(socket.socket())\n        self.stream.connect(('127.0.0.1', self.port),\n                            callback=self.handle_connect)\n        self.callback = callback\n\n    def handle_connect(self):\n        logging.debug(\"handle_connect\")\n        self.stream.write(utf8(self.request_data + \"\\n\"))\n        self.stream.read_until(b'\\n', callback=self.handle_read)\n\n    def handle_read(self, data):\n        logging.debug(\"handle_read\")\n        self.stream.close()\n        self.callback(self.process_response(data))\n\n\nclass GeneratorCapClient(BaseCapClient):\n    @return_future\n    @gen.engine\n    def capitalize(self, request_data, callback):\n        logging.debug('capitalize')\n        stream = IOStream(socket.socket())\n        logging.debug('connecting')\n        yield gen.Task(stream.connect, ('127.0.0.1', self.port))\n        stream.write(utf8(request_data + '\\n'))\n        logging.debug('reading')\n        data = yield gen.Task(stream.read_until, b'\\n')\n        logging.debug('returning')\n        stream.close()\n        callback(self.process_response(data))\n\n\nclass ClientTestMixin(object):\n    def setUp(self):\n        super(ClientTestMixin, self).setUp()  # type: ignore\n        self.server = CapServer()\n        sock, port = bind_unused_port()\n        self.server.add_sockets([sock])\n        self.client = self.client_class(port=port)\n\n    def tearDown(self):\n        self.server.stop()\n        super(ClientTestMixin, self).tearDown()  # type: ignore\n\n    def test_callback(self):\n        self.client.capitalize(\"hello\", callback=self.stop)\n        result = self.wait()\n        self.assertEqual(result, \"HELLO\")\n\n    def test_callback_error(self):\n        self.client.capitalize(\"HELLO\", callback=self.stop)\n        self.assertRaisesRegexp(CapError, \"already capitalized\", self.wait)\n\n    def test_future(self):\n        future = self.client.capitalize(\"hello\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertEqual(future.result(), \"HELLO\")\n\n    def test_future_error(self):\n        future = self.client.capitalize(\"HELLO\")\n        self.io_loop.add_future(future, self.stop)\n        self.wait()\n        self.assertRaisesRegexp(CapError, \"already capitalized\", future.result)\n\n    def test_generator(self):\n        @gen.engine\n        def f():\n            result = yield self.client.capitalize(\"hello\")\n            self.assertEqual(result, \"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n    def test_generator_error(self):\n        @gen.engine\n        def f():\n            with self.assertRaisesRegexp(CapError, \"already capitalized\"):\n                yield self.client.capitalize(\"HELLO\")\n            self.stop()\n        f()\n        self.wait()\n\n\nclass ManualClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = ManualCapClient\n\n\nclass DecoratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = DecoratorCapClient\n\n\nclass GeneratorClientTest(ClientTestMixin, AsyncTestCase):\n    client_class = GeneratorCapClient\n\n\n@unittest.skipIf(futures is None, \"concurrent.futures module not present\")\nclass RunOnExecutorTest(AsyncTestCase):\n    @gen_test\n    def test_no_calling(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_no_args(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @gen_test\n    def test_call_with_executor(self):\n        class Object(object):\n            def __init__(self):\n                self.__executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor(executor='_Object__executor')\n            def f(self):\n                return 42\n\n        o = Object()\n        answer = yield o.f()\n        self.assertEqual(answer, 42)\n\n    @skipBefore35\n    @gen_test\n    def test_async_await(self):\n        class Object(object):\n            def __init__(self):\n                self.executor = futures.thread.ThreadPoolExecutor(1)\n\n            @run_on_executor()\n            def f(self):\n                return 42\n\n        o = Object()\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f():\n            answer = await o.f()\n            return answer\n        \"\"\")\n        result = yield namespace['f']()\n        self.assertEqual(result, 42)\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 850ms\nPrepared 1 package in 1.14s\nInstalled 1 package in 0.65ms\n + tornado==5.1.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7)\nResolved 29 packages in 16ms\nInstalled 29 packages in 163ms\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_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7\n.......................................\ncollected 39 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::ManualClientTest::test_callback\nPASSED r2e_tests.test_1::ManualClientTest::test_callback_error\nPASSED r2e_tests.test_1::ManualClientTest::test_future\nPASSED r2e_tests.test_1::ManualClientTest::test_future_error\nPASSED r2e_tests.test_1::ManualClientTest::test_generator\nPASSED r2e_tests.test_1::ManualClientTest::test_generator_error\nPASSED r2e_tests.test_1::MiscFutureTest::test_future_set_result_unless_cancelled\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future_gen\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_positional\nPASSED r2e_tests.test_1::ReturnFutureTest::test_delayed_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_error_in_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_future_traceback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_immediate_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_kw_only_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_result_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_result_future_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_pos\nPASSED r2e_tests.test_1::ReturnFutureTest::test_return_value\nPASSED r2e_tests.test_1::ReturnFutureTest::test_uncaught_exception_log\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_async_await\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_call_with_executor\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_call_with_no_args\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_no_calling\n=================== 39 passed in 0.09s ===================\n",
    "new_commit_res_stderr": "",
    "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_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7\n.......................................\ncollected 39 items\n\n=================================== ERRORS =====================================\n__________ RunOnExecutorTest.test_async_await __________\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_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/tornado/testing.py\", line 118, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/tornado/testing.py\", line 519, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/tornado/ioloop.py\", line 582, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/tornado/gen.py\", line 1107, in run\n    yielded = self.gen.throw(*exc_info)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/types.py\", line 217, in throw\n    return self.__wrapped.throw(tp, *rest)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/r2e_tests/test_1.py\", line 449, in test_async_await\n    result = yield namespace['f']()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_e4e9dbb6314a358bb55ce5bda6e6e45cf91737d7/tornado/gen.py\", line 1099, in run\n    value = future.result()\n  File \"<string>\", line 3, in f\nTypeError: object Future can't be used in 'await' expression\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback\nPASSED r2e_tests.test_1::DecoratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future\nPASSED r2e_tests.test_1::DecoratorClientTest::test_future_error\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator\nPASSED r2e_tests.test_1::DecoratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback\nPASSED r2e_tests.test_1::GeneratorClientTest::test_callback_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future\nPASSED r2e_tests.test_1::GeneratorClientTest::test_future_error\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator\nPASSED r2e_tests.test_1::GeneratorClientTest::test_generator_error\nPASSED r2e_tests.test_1::ManualClientTest::test_callback\nPASSED r2e_tests.test_1::ManualClientTest::test_callback_error\nPASSED r2e_tests.test_1::ManualClientTest::test_future\nPASSED r2e_tests.test_1::ManualClientTest::test_future_error\nPASSED r2e_tests.test_1::ManualClientTest::test_generator\nPASSED r2e_tests.test_1::ManualClientTest::test_generator_error\nPASSED r2e_tests.test_1::MiscFutureTest::test_future_set_result_unless_cancelled\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_async_future_gen\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_callback_positional\nPASSED r2e_tests.test_1::ReturnFutureTest::test_delayed_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_error_in_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_future_traceback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_immediate_failure\nPASSED r2e_tests.test_1::ReturnFutureTest::test_kw_only_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_result_future\nPASSED r2e_tests.test_1::ReturnFutureTest::test_no_result_future_callback\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_kw\nPASSED r2e_tests.test_1::ReturnFutureTest::test_none_callback_pos\nPASSED r2e_tests.test_1::ReturnFutureTest::test_return_value\nPASSED r2e_tests.test_1::ReturnFutureTest::test_uncaught_exception_log\nERROR r2e_tests.test_1::RunOnExecutorTest::test_async_await\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_call_with_executor\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_call_with_no_args\nPASSED r2e_tests.test_1::RunOnExecutorTest::test_no_calling\n=================== 1 error, 38 passed in 0.08s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/concurrent.py tornado/test/concurrent_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
Title: Cannot await methods decorated with @run_on_executor - Raises TypeError

**Description**

When using the `@run_on_executor` decorator, attempting to `await` the decorated method results in a `TypeError` because the returned future is not compatible with `await` expressions.

**Example Code:**

```python
from concurrent import futures
from tornado.concurrent import run_on_executor

class Object:
    def __init__(self):
        self.executor = futures.ThreadPoolExecutor(1)

    @run_on_executor()
    def f(self):
        return 42

async def async_function():
    o = Object()
    result = await o.f()
    return result
```

**Expected Behavior:**
The `await o.f()` call should return `42` without any errors.

**Actual Behavior:**
Raises `TypeError: object Future can't be used in 'await' expression`
[/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/concurrent.py
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for working with ``Future`` objects.

``Futures`` are a pattern for concurrent programming introduced in
Python 3.2 in the `concurrent.futures` package, and also adopted (in a
slightly different form) in Python 3.4's `asyncio` package. This
package defines a ``Future`` class that is an alias for `asyncio.Future`
when available, and a compatible implementation for older versions of
Python. It also includes some utility functions for interacting with
``Future`` objects.

While this package is an important part of Tornado's internal
implementation, applications rarely need to interact with it
directly.
"""
from __future__ import absolute_import, division, print_function

import functools
import platform
import textwrap
import traceback
import sys

from tornado.log import app_log
from tornado.stack_context import ExceptionStackContext, wrap
from tornado.util import raise_exc_info, ArgReplacer, is_finalizing

try:
    from concurrent import futures
except ImportError:
    futures = None

try:
    import asyncio
except ImportError:
    asyncio = None

try:
    import typing
except ImportError:
    typing = None


# Can the garbage collector handle cycles that include __del__ methods?
# This is true in cpython beginning with version 3.4 (PEP 442).
_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
                        sys.version_info >= (3, 4))


class ReturnValueIgnoredError(Exception):
    pass

# This class and associated code in the future object is derived
# from the Trollius project, a backport of asyncio to Python 2.x - 3.x


class _TracebackLogger(object):
    """Helper to log a traceback upon destruction if not cleared.

    This solves a nasty problem with Futures and Tasks that have an
    exception set: if nobody asks for the exception, the exception is
    never logged.  This violates the Zen of Python: 'Errors should
    never pass silently.  Unless explicitly silenced.'

    However, we don't want to log the exception as soon as
    set_exception() is called: if the calling code is written
    properly, it will get the exception and handle it properly.  But
    we *do* want to log it if result() or exception() was never called
    -- otherwise developers waste a lot of time wondering why their
    buggy code fails silently.

    An earlier attempt added a __del__() method to the Future class
    itself, but this backfired because the presence of __del__()
    prevents garbage collection from breaking cycles.  A way out of
    this catch-22 is to avoid having a __del__() method on the Future
    class itself, but instead to have a reference to a helper object
    with a __del__() method that logs the traceback, where we ensure
    that the helper object doesn't participate in cycles, and only the
    Future has a reference to it.

    The helper object is added when set_exception() is called.  When
    the Future is collected, and the helper is present, the helper
    object is also collected, and its __del__() method will log the
    traceback.  When the Future's result() or exception() method is
    called (and a helper object is present), it removes the the helper
    object, after calling its clear() method to prevent it from
    logging.

    One downside is that we do a fair amount of work to extract the
    traceback from the exception, even when it is never logged.  It
    would seem cheaper to just store the exception object, but that
    references the traceback, which references stack frames, which may
    reference the Future, which references the _TracebackLogger, and
    then the _TracebackLogger would be included in a cycle, which is
    what we're trying to avoid!  As an optimization, we don't
    immediately format the exception; we only do the work when
    activate() is called, which call is delayed until after all the
    Future's callbacks have run.  Since usually a Future has at least
    one callback (typically set by 'yield From') and usually that
    callback extracts the callback, thereby removing the need to
    format the exception.

    PS. I don't claim credit for this solution.  I first heard of it
    in a discussion about closing files when they are collected.
    """

    __slots__ = ('exc_info', 'formatted_tb')

    def __init__(self, exc_info):
        self.exc_info = exc_info
        self.formatted_tb = None

    def activate(self):
        exc_info = self.exc_info
        if exc_info is not None:
            self.exc_info = None
            self.formatted_tb = traceback.format_exception(*exc_info)

    def clear(self):
        self.exc_info = None
        self.formatted_tb = None

    def __del__(self, is_finalizing=is_finalizing):
        if not is_finalizing() and self.formatted_tb:
            app_log.error('Future exception was never retrieved: %s',
                          ''.join(self.formatted_tb).rstrip())


class Future(object):
    """Placeholder for an asynchronous result.

    A ``Future`` encapsulates the result of an asynchronous
    operation.  In synchronous applications ``Futures`` are used
    to wait for the result from a thread or process pool; in
    Tornado they are normally used with `.IOLoop.add_future` or by
    yielding them in a `.gen.coroutine`.

    `tornado.concurrent.Future` is an alias for `asyncio.Future` when
    that package is available (Python 3.4+). Unlike
    `concurrent.futures.Future`, the ``Futures`` used by Tornado and
    `asyncio` are not thread-safe (and therefore faster for use with
    single-threaded event loops).

    In addition to ``exception`` and ``set_exception``, Tornado's
    ``Future`` implementation supports storing an ``exc_info`` triple
    to support better tracebacks on Python 2. To set an ``exc_info``
    triple, use `future_set_exc_info`, and to retrieve one, call
    `result()` (which will raise it).

    .. versionchanged:: 4.0
       `tornado.concurrent.Future` is always a thread-unsafe ``Future``
       with support for the ``exc_info`` methods.  Previously it would
       be an alias for the thread-safe `concurrent.futures.Future`
       if that package was available and fall back to the thread-unsafe
       implementation if it was not.

    .. versionchanged:: 4.1
       If a `.Future` contains an error but that error is never observed
       (by calling ``result()``, ``exception()``, or ``exc_info()``),
       a stack trace will be logged when the `.Future` is garbage collected.
       This normally indicates an error in the application, but in cases
       where it results in undesired logging it may be necessary to
       suppress the logging by ensuring that the exception is observed:
       ``f.add_done_callback(lambda f: f.exception())``.

    .. versionchanged:: 5.0

       This class was previoiusly available under the name
       ``TracebackFuture``. This name, which was deprecated since
       version 4.0, has been removed. When `asyncio` is available
       ``tornado.concurrent.Future`` is now an alias for
       `asyncio.Future`. Like `asyncio.Future`, callbacks are now
       always scheduled on the `.IOLoop` and are never run
       synchronously.

    """
    def __init__(self):
        self._done = False
        self._result = None
        self._exc_info = None

        self._log_traceback = False   # Used for Python >= 3.4
        self._tb_logger = None        # Used for Python <= 3.3

        self._callbacks = []

    # Implement the Python 3.5 Awaitable protocol if possible
    # (we can't use return and yield together until py33).
    if sys.version_info >= (3, 3):
        exec(textwrap.dedent("""
        def __await__(self):
            return (yield self)
        """))
    else:
        # Py2-compatible version for use with cython.
        def __await__(self):
            result = yield self
            # StopIteration doesn't take args before py33,
            # but Cython recognizes the args tuple.
            e = StopIteration()
            e.args = (result,)
            raise e

    def cancel(self):
        """Cancel the operation, if possible.

        Tornado ``Futures`` do not support cancellation, so this method always
        returns False.
        """
        return False

    def cancelled(self):
        """Returns True if the operation has been cancelled.

        Tornado ``Futures`` do not support cancellation, so this method
        always returns False.
        """
        return False

    def running(self):
        """Returns True if this operation is currently running."""
        return not self._done

    def done(self):
        """Returns True if the future has finished running."""
        return self._done

    def _clear_tb_log(self):
        self._log_traceback = False
        if self._tb_logger is not None:
            self._tb_logger.clear()
            self._tb_logger = None

    def result(self, timeout=None):
        """If the operation succeeded, return its result.  If it failed,
        re-raise its exception.

        This method takes a ``timeout`` argument for compatibility with
        `concurrent.futures.Future` but it is an error to call it
        before the `Future` is done, so the ``timeout`` is never used.
        """
        self._clear_tb_log()
        if self._result is not None:
            return self._result
        if self._exc_info is not None:
            try:
                raise_exc_info(self._exc_info)
            finally:
                self = None
        self._check_done()
        return self._result

    def exception(self, timeout=None):
        """If the operation raised an exception, return the `Exception`
        object.  Otherwise returns None.

        This method takes a ``timeout`` argument for compatibility with
        `concurrent.futures.Future` but it is an error to call it
        before the `Future` is done, so the ``timeout`` is never used.
        """
        self._clear_tb_log()
        if self._exc_info is not None:
            return self._exc_info[1]
        else:
            self._check_done()
            return None

    def add_done_callback(self, fn):
        """Attaches the given callback to the `Future`.

        It will be invoked with the `Future` as its argument when the Future
        has finished running and its result is available.  In Tornado
        consider using `.IOLoop.add_future` instead of calling
        `add_done_callback` directly.
        """
        if self._done:
            from tornado.ioloop import IOLoop
            IOLoop.current().add_callback(fn, self)
        else:
            self._callbacks.append(fn)

    def set_result(self, result):
        """Sets the result of a ``Future``.

        It is undefined to call any of the ``set`` methods more than once
        on the same object.
        """
        self._result = result
        self._set_done()

    def set_exception(self, exception):
        """Sets the exception of a ``Future.``"""
        self.set_exc_info(
            (exception.__class__,
             exception,
             getattr(exception, '__traceback__', None)))

    def exc_info(self):
        """Returns a tuple in the same format as `sys.exc_info` or None.

        .. versionadded:: 4.0
        """
        self._clear_tb_log()
        return self._exc_info

    def set_exc_info(self, exc_info):
        """Sets the exception information of a ``Future.``

        Preserves tracebacks on Python 2.

        .. versionadded:: 4.0
        """
        self._exc_info = exc_info
        self._log_traceback = True
        if not _GC_CYCLE_FINALIZERS:
            self._tb_logger = _TracebackLogger(exc_info)

        try:
            self._set_done()
        finally:
            # Activate the logger after all callbacks have had a
            # chance to call result() or exception().
            if self._log_traceback and self._tb_logger is not None:
                self._tb_logger.activate()
        self._exc_info = exc_info

    def _check_done(self):
        if not self._done:
            raise Exception("DummyFuture does not support blocking for results")

    def _set_done(self):
        self._done = True
        if self._callbacks:
            from tornado.ioloop import IOLoop
            loop = IOLoop.current()
            for cb in self._callbacks:
                loop.add_callback(cb, self)
            self._callbacks = None

    # On Python 3.3 or older, objects with a destructor part of a reference
    # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to
    # the PEP 442.
    if _GC_CYCLE_FINALIZERS:
        def __del__(self, is_finalizing=is_finalizing):
            if is_finalizing() or not self._log_traceback:
                # set_exception() was not called, or result() or exception()
                # has consumed the exception
                return

            tb = traceback.format_exception(*self._exc_info)

            app_log.error('Future %r exception was never retrieved: %s',
                          self, ''.join(tb).rstrip())


if asyncio is not None:
    Future = asyncio.Future  # noqa

if futures is None:
    FUTURES = Future  # type: typing.Union[type, typing.Tuple[type, ...]]
else:
    FUTURES = (futures.Future, Future)


def is_future(x):
    return isinstance(x, FUTURES)


class DummyExecutor(object):
    def submit(self, fn, *args, **kwargs):
        future = Future()
        try:
            future_set_result_unless_cancelled(future, fn(*args, **kwargs))
        except Exception:
            future_set_exc_info(future, sys.exc_info())
        return future

    def shutdown(self, wait=True):
        pass


dummy_executor = DummyExecutor()


def run_on_executor(*args, **kwargs):
    """Decorator to run a synchronous method asynchronously on an executor.

    The decorated method may be called with a ``callback`` keyword
    argument and returns a future.

    The executor to be used is determined by the ``executor``
    attributes of ``self``. To use a different attribute name, pass a
    keyword argument to the decorator::

        @run_on_executor(executor='_thread_pool')
        def foo(self):
            pass

    This decorator should not be confused with the similarly-named
    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``
    when *calling* a blocking method is recommended instead of using
    this decorator when *defining* a method. If compatibility with older
    versions of Tornado is required, consider defining an executor
    and using ``executor.submit()`` at the call site.

    .. versionchanged:: 4.2
       Added keyword arguments to use alternative attributes.

    .. versionchanged:: 5.0
       Always uses the current IOLoop instead of ``self.io_loop``.
    """
    def run_on_executor_decorator(fn):
        executor = kwargs.get("executor", "executor")

        @functools.wraps(fn)
        def wrapper(self, *args, **kwargs):
            callback = kwargs.pop("callback", None)
            future = getattr(self, executor).submit(fn, self, *args, **kwargs)
            if callback:
                from tornado.ioloop import IOLoop
                IOLoop.current().add_future(
                    future, lambda future: callback(future.result()))
            return future
        return wrapper
    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator


_NO_RESULT = object()


def return_future(f):
    """Decorator to make a function that returns via callback return a
    `Future`.

    This decorator was provided to ease the transition from
    callback-oriented code to coroutines. It is not recommended for
    new code.

    The wrapped function should take a ``callback`` keyword argument
    and invoke it with one argument when it has finished.  To signal failure,
    the function can simply raise an exception (which will be
    captured by the `.StackContext` and passed along to the ``Future``).

    From the caller's perspective, the callback argument is optional.
    If one is given, it will be invoked when the function is complete
    with ``Future.result()`` as an argument.  If the function fails, the
    callback will not be run and an exception will be raised into the
    surrounding `.StackContext`.

    If no callback is given, the caller should use the ``Future`` to
    wait for the function to complete (perhaps by yielding it in a
    `.gen.engine` function, or passing it to `.IOLoop.add_future`).

    Usage:

    .. testcode::

        @return_future
        def future_func(arg1, arg2, callback):
            # Do stuff (possibly asynchronous)
            callback(result)

        @gen.engine
        def caller(callback):
            yield future_func(arg1, arg2)
            callback()

    ..

    Note that ``@return_future`` and ``@gen.engine`` can be applied to the
    same function, provided ``@return_future`` appears first.  However,
    consider using ``@gen.coroutine`` instead of this combination.

    """
    replacer = ArgReplacer(f, 'callback')

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = Future()
        callback, args, kwargs = replacer.replace(
            lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value),
            args, kwargs)

        def handle_error(typ, value, tb):
            future_set_exc_info(future, (typ, value, tb))
            return True
        exc_info = None
        with ExceptionStackContext(handle_error):
            try:
                result = f(*args, **kwargs)
                if result is not None:
                    raise ReturnValueIgnoredError(
                        "@return_future should not be used with functions "
                        "that return values")
            except:
                exc_info = sys.exc_info()
                raise
        if exc_info is not None:
            # If the initial synchronous part of f() raised an exception,
            # go ahead and raise it to the caller directly without waiting
            # for them to inspect the Future.
            future.result()

        # If the caller passed in a callback, schedule it to be called
        # when the future resolves.  It is important that this happens
        # just before we return the future, or else we risk confusing
        # stack contexts with multiple exceptions (one here with the
        # immediate exception, and again when the future resolves and
        # the callback triggers its exception by calling future.result()).
        if callback is not None:
            def run_callback(future):
                result = future.result()
                if result is _NO_RESULT:
                    callback()
                else:
                    callback(future.result())
            future_add_done_callback(future, wrap(run_callback))
        return future
    return wrapper


def chain_future(a, b):
    """Chain two futures together so that when one completes, so does the other.

    The result (success or failure) of ``a`` will be copied to ``b``, unless
    ``b`` has already been completed or cancelled by the time ``a`` finishes.

    .. versionchanged:: 5.0

       Now accepts both Tornado/asyncio `Future` objects and
       `concurrent.futures.Future`.

    """
    def copy(future):
        assert future is a
        if b.done():
            return
        if (hasattr(a, 'exc_info') and
                a.exc_info() is not None):
            future_set_exc_info(b, a.exc_info())
        elif a.exception() is not None:
            b.set_exception(a.exception())
        else:
            b.set_result(a.result())
    if isinstance(a, Future):
        future_add_done_callback(a, copy)
    else:
        # concurrent.futures.Future
        from tornado.ioloop import IOLoop
        IOLoop.current().add_future(a, copy)


def future_set_result_unless_cancelled(future, value):
    """Set the given ``value`` as the `Future`'s result, if not cancelled.

    Avoids asyncio.InvalidStateError when calling set_result() on
    a cancelled `asyncio.Future`.

    .. versionadded:: 5.0
    """
    if not future.cancelled():
        future.set_result(value)


def future_set_exc_info(future, exc_info):
    """Set the given ``exc_info`` as the `Future`'s exception.

    Understands both `asyncio.Future` and Tornado's extensions to
    enable better tracebacks on Python 2.

    .. versionadded:: 5.0
    """
    if hasattr(future, 'set_exc_info'):
        # Tornado's Future
        future.set_exc_info(exc_info)
    else:
        # asyncio.Future
        future.set_exception(exc_info[1])


def future_add_done_callback(future, callback):
    """Arrange to call ``callback`` when ``future`` is complete.

    ``callback`` is invoked with one argument, the ``future``.

    If ``future`` is already done, ``callback`` is invoked immediately.
    This may differ from the behavior of ``Future.add_done_callback``,
    which makes no such guarantee.

    .. versionadded:: 5.0
    """
    if future.done():
        callback(future)
    else:
        future.add_done_callback(callback)

```
--- 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: Cannot await methods decorated with @run_on_executor - Raises TypeError

**Description**

When using the `@run_on_executor` decorator, attempting to `await` the decorated method results in a `TypeError` because the returned future is not compatible with `await` expressions.

**Example Code:**

```python
from concurrent import futures
from tornado.concurrent import run_on_executor

class Object:
    def __init__(self):
        self.executor = futures.ThreadPoolExecutor(1)

    @run_on_executor()
    def f(self):
        return 42

async def async_function():
    o = Object()
    result = await o.f()
    return result
```

**Expected Behavior:**
The `await o.f()` call should return `42` without any errors.

**Actual Behavior:**
Raises `TypeError: object Future can't be used in 'await' expression`
[/ISSUE]
{
    "DecoratorClientTest.test_callback": "PASSED",
    "DecoratorClientTest.test_callback_error": "PASSED",
    "DecoratorClientTest.test_future": "PASSED",
    "DecoratorClientTest.test_future_error": "PASSED",
    "DecoratorClientTest.test_generator": "PASSED",
    "DecoratorClientTest.test_generator_error": "PASSED",
    "GeneratorClientTest.test_callback": "PASSED",
    "GeneratorClientTest.test_callback_error": "PASSED",
    "GeneratorClientTest.test_future": "PASSED",
    "GeneratorClientTest.test_future_error": "PASSED",
    "GeneratorClientTest.test_generator": "PASSED",
    "GeneratorClientTest.test_generator_error": "PASSED",
    "ManualClientTest.test_callback": "PASSED",
    "ManualClientTest.test_callback_error": "PASSED",
    "ManualClientTest.test_future": "PASSED",
    "ManualClientTest.test_future_error": "PASSED",
    "ManualClientTest.test_generator": "PASSED",
    "ManualClientTest.test_generator_error": "PASSED",
    "MiscFutureTest.test_future_set_result_unless_cancelled": "PASSED",
    "ReturnFutureTest.test_async_future": "PASSED",
    "ReturnFutureTest.test_async_future_gen": "PASSED",
    "ReturnFutureTest.test_callback_kw": "PASSED",
    "ReturnFutureTest.test_callback_positional": "PASSED",
    "ReturnFutureTest.test_delayed_failure": "PASSED",
    "ReturnFutureTest.test_error_in_callback": "PASSED",
    "ReturnFutureTest.test_future_traceback": "PASSED",
    "ReturnFutureTest.test_immediate_failure": "PASSED",
    "ReturnFutureTest.test_kw_only_callback": "PASSED",
    "ReturnFutureTest.test_no_callback": "PASSED",
    "ReturnFutureTest.test_no_result_future": "PASSED",
    "ReturnFutureTest.test_no_result_future_callback": "PASSED",
    "ReturnFutureTest.test_none_callback_kw": "PASSED",
    "ReturnFutureTest.test_none_callback_pos": "PASSED",
    "ReturnFutureTest.test_return_value": "PASSED",
    "ReturnFutureTest.test_uncaught_exception_log": "PASSED",
    "RunOnExecutorTest.test_async_await": "PASSED",
    "RunOnExecutorTest.test_call_with_executor": "PASSED",
    "RunOnExecutorTest.test_call_with_no_args": "PASSED",
    "RunOnExecutorTest.test_no_calling": "PASSED"
}
diff --git a/tornado/concurrent.py b/tornado/concurrent.py
index 1a79f1e1..aa38bb99 100644
--- a/tornado/concurrent.py
+++ b/tornado/concurrent.py
@@ -421,6 +421,10 @@ def run_on_executor(*args, **kwargs):
 
     .. versionchanged:: 5.0
        Always uses the current IOLoop instead of ``self.io_loop``.
+
+    .. versionchanged:: 5.1
+       Returns a `.Future` compatible with ``await`` instead of a
+       `concurrent.futures.Future`.
     """
     def run_on_executor_decorator(fn):
         executor = kwargs.get("executor", "executor")
@@ -428,12 +432,14 @@ def run_on_executor(*args, **kwargs):
         @functools.wraps(fn)
         def wrapper(self, *args, **kwargs):
             callback = kwargs.pop("callback", None)
-            future = getattr(self, executor).submit(fn, self, *args, **kwargs)
+            async_future = Future()
+            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)
+            chain_future(conc_future, async_future)
             if callback:
                 from tornado.ioloop import IOLoop
                 IOLoop.current().add_future(
-                    future, lambda future: callback(future.result()))
-            return future
+                    async_future, lambda future: callback(future.result()))
+            return async_future
         return wrapper
     if args and kwargs:
         raise ValueError("cannot combine positional and keyword args")

{"tornado/concurrent.py": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\n``Futures`` are a pattern for concurrent programming introduced in\nPython 3.2 in the `concurrent.futures` package, and also adopted (in a\nslightly different form) in Python 3.4's `asyncio` package. This\npackage defines a ``Future`` class that is an alias for `asyncio.Future`\nwhen available, and a compatible implementation for older versions of\nPython. It also includes some utility functions for interacting with\n``Future`` objects.\n\nWhile this package is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport functools\nimport platform\nimport textwrap\nimport traceback\nimport sys\n\nfrom tornado.log import app_log\nfrom tornado.stack_context import ExceptionStackContext, wrap\nfrom tornado.util import raise_exc_info, ArgReplacer, is_finalizing\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import typing\nexcept ImportError:\n    typing = None\n\n\n# Can the garbage collector handle cycles that include __del__ methods?\n# This is true in cpython beginning with version 3.4 (PEP 442).\n_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and\n                        sys.version_info >= (3, 4))\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n# This class and associated code in the future object is derived\n# from the Trollius project, a backport of asyncio to Python 2.x - 3.x\n\n\nclass _TracebackLogger(object):\n    \"\"\"Helper to log a traceback upon destruction if not cleared.\n\n    This solves a nasty problem with Futures and Tasks that have an\n    exception set: if nobody asks for the exception, the exception is\n    never logged.  This violates the Zen of Python: 'Errors should\n    never pass silently.  Unless explicitly silenced.'\n\n    However, we don't want to log the exception as soon as\n    set_exception() is called: if the calling code is written\n    properly, it will get the exception and handle it properly.  But\n    we *do* want to log it if result() or exception() was never called\n    -- otherwise developers waste a lot of time wondering why their\n    buggy code fails silently.\n\n    An earlier attempt added a __del__() method to the Future class\n    itself, but this backfired because the presence of __del__()\n    prevents garbage collection from breaking cycles.  A way out of\n    this catch-22 is to avoid having a __del__() method on the Future\n    class itself, but instead to have a reference to a helper object\n    with a __del__() method that logs the traceback, where we ensure\n    that the helper object doesn't participate in cycles, and only the\n    Future has a reference to it.\n\n    The helper object is added when set_exception() is called.  When\n    the Future is collected, and the helper is present, the helper\n    object is also collected, and its __del__() method will log the\n    traceback.  When the Future's result() or exception() method is\n    called (and a helper object is present), it removes the the helper\n    object, after calling its clear() method to prevent it from\n    logging.\n\n    One downside is that we do a fair amount of work to extract the\n    traceback from the exception, even when it is never logged.  It\n    would seem cheaper to just store the exception object, but that\n    references the traceback, which references stack frames, which may\n    reference the Future, which references the _TracebackLogger, and\n    then the _TracebackLogger would be included in a cycle, which is\n    what we're trying to avoid!  As an optimization, we don't\n    immediately format the exception; we only do the work when\n    activate() is called, which call is delayed until after all the\n    Future's callbacks have run.  Since usually a Future has at least\n    one callback (typically set by 'yield From') and usually that\n    callback extracts the callback, thereby removing the need to\n    format the exception.\n\n    PS. I don't claim credit for this solution.  I first heard of it\n    in a discussion about closing files when they are collected.\n    \"\"\"\n\n    __slots__ = ('exc_info', 'formatted_tb')\n\n    def __init__(self, exc_info):\n        self.exc_info = exc_info\n        self.formatted_tb = None\n\n    def activate(self):\n        exc_info = self.exc_info\n        if exc_info is not None:\n            self.exc_info = None\n            self.formatted_tb = traceback.format_exception(*exc_info)\n\n    def clear(self):\n        self.exc_info = None\n        self.formatted_tb = None\n\n    def __del__(self, is_finalizing=is_finalizing):\n        if not is_finalizing() and self.formatted_tb:\n            app_log.error('Future exception was never retrieved: %s',\n                          ''.join(self.formatted_tb).rstrip())\n\n\nclass Future(object):\n    \"\"\"Placeholder for an asynchronous result.\n\n    A ``Future`` encapsulates the result of an asynchronous\n    operation.  In synchronous applications ``Futures`` are used\n    to wait for the result from a thread or process pool; in\n    Tornado they are normally used with `.IOLoop.add_future` or by\n    yielding them in a `.gen.coroutine`.\n\n    `tornado.concurrent.Future` is an alias for `asyncio.Future` when\n    that package is available (Python 3.4+). Unlike\n    `concurrent.futures.Future`, the ``Futures`` used by Tornado and\n    `asyncio` are not thread-safe (and therefore faster for use with\n    single-threaded event loops).\n\n    In addition to ``exception`` and ``set_exception``, Tornado's\n    ``Future`` implementation supports storing an ``exc_info`` triple\n    to support better tracebacks on Python 2. To set an ``exc_info``\n    triple, use `future_set_exc_info`, and to retrieve one, call\n    `result()` (which will raise it).\n\n    .. versionchanged:: 4.0\n       `tornado.concurrent.Future` is always a thread-unsafe ``Future``\n       with support for the ``exc_info`` methods.  Previously it would\n       be an alias for the thread-safe `concurrent.futures.Future`\n       if that package was available and fall back to the thread-unsafe\n       implementation if it was not.\n\n    .. versionchanged:: 4.1\n       If a `.Future` contains an error but that error is never observed\n       (by calling ``result()``, ``exception()``, or ``exc_info()``),\n       a stack trace will be logged when the `.Future` is garbage collected.\n       This normally indicates an error in the application, but in cases\n       where it results in undesired logging it may be necessary to\n       suppress the logging by ensuring that the exception is observed:\n       ``f.add_done_callback(lambda f: f.exception())``.\n\n    .. versionchanged:: 5.0\n\n       This class was previoiusly available under the name\n       ``TracebackFuture``. This name, which was deprecated since\n       version 4.0, has been removed. When `asyncio` is available\n       ``tornado.concurrent.Future`` is now an alias for\n       `asyncio.Future`. Like `asyncio.Future`, callbacks are now\n       always scheduled on the `.IOLoop` and are never run\n       synchronously.\n\n    \"\"\"\n    def __init__(self):\n        self._done = False\n        self._result = None\n        self._exc_info = None\n\n        self._log_traceback = False   # Used for Python >= 3.4\n        self._tb_logger = None        # Used for Python <= 3.3\n\n        self._callbacks = []\n\n    # Implement the Python 3.5 Awaitable protocol if possible\n    # (we can't use return and yield together until py33).\n    if sys.version_info >= (3, 3):\n        exec(textwrap.dedent(\"\"\"\n        def __await__(self):\n            return (yield self)\n        \"\"\"))\n    else:\n        # Py2-compatible version for use with cython.\n        def __await__(self):\n            result = yield self\n            # StopIteration doesn't take args before py33,\n            # but Cython recognizes the args tuple.\n            e = StopIteration()\n            e.args = (result,)\n            raise e\n\n    def cancel(self):\n        \"\"\"Cancel the operation, if possible.\n\n        Tornado ``Futures`` do not support cancellation, so this method always\n        returns False.\n        \"\"\"\n        return False\n\n    def cancelled(self):\n        \"\"\"Returns True if the operation has been cancelled.\n\n        Tornado ``Futures`` do not support cancellation, so this method\n        always returns False.\n        \"\"\"\n        return False\n\n    def running(self):\n        \"\"\"Returns True if this operation is currently running.\"\"\"\n        return not self._done\n\n    def done(self):\n        \"\"\"Returns True if the future has finished running.\"\"\"\n        return self._done\n\n    def _clear_tb_log(self):\n        self._log_traceback = False\n        if self._tb_logger is not None:\n            self._tb_logger.clear()\n            self._tb_logger = None\n\n    def result(self, timeout=None):\n        \"\"\"If the operation succeeded, return its result.  If it failed,\n        re-raise its exception.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._result is not None:\n            return self._result\n        if self._exc_info is not None:\n            try:\n                raise_exc_info(self._exc_info)\n            finally:\n                self = None\n        self._check_done()\n        return self._result\n\n    def exception(self, timeout=None):\n        \"\"\"If the operation raised an exception, return the `Exception`\n        object.  Otherwise returns None.\n\n        This method takes a ``timeout`` argument for compatibility with\n        `concurrent.futures.Future` but it is an error to call it\n        before the `Future` is done, so the ``timeout`` is never used.\n        \"\"\"\n        self._clear_tb_log()\n        if self._exc_info is not None:\n            return self._exc_info[1]\n        else:\n            self._check_done()\n            return None\n\n    def add_done_callback(self, fn):\n        \"\"\"Attaches the given callback to the `Future`.\n\n        It will be invoked with the `Future` as its argument when the Future\n        has finished running and its result is available.  In Tornado\n        consider using `.IOLoop.add_future` instead of calling\n        `add_done_callback` directly.\n        \"\"\"\n        if self._done:\n            from tornado.ioloop import IOLoop\n            IOLoop.current().add_callback(fn, self)\n        else:\n            self._callbacks.append(fn)\n\n    def set_result(self, result):\n        \"\"\"Sets the result of a ``Future``.\n\n        It is undefined to call any of the ``set`` methods more than once\n        on the same object.\n        \"\"\"\n        self._result = result\n        self._set_done()\n\n    def set_exception(self, exception):\n        \"\"\"Sets the exception of a ``Future.``\"\"\"\n        self.set_exc_info(\n            (exception.__class__,\n             exception,\n             getattr(exception, '__traceback__', None)))\n\n    def exc_info(self):\n        \"\"\"Returns a tuple in the same format as `sys.exc_info` or None.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._clear_tb_log()\n        return self._exc_info\n\n    def set_exc_info(self, exc_info):\n        \"\"\"Sets the exception information of a ``Future.``\n\n        Preserves tracebacks on Python 2.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self._exc_info = exc_info\n        self._log_traceback = True\n        if not _GC_CYCLE_FINALIZERS:\n            self._tb_logger = _TracebackLogger(exc_info)\n\n        try:\n            self._set_done()\n        finally:\n            # Activate the logger after all callbacks have had a\n            # chance to call result() or exception().\n            if self._log_traceback and self._tb_logger is not None:\n                self._tb_logger.activate()\n        self._exc_info = exc_info\n\n    def _check_done(self):\n        if not self._done:\n            raise Exception(\"DummyFuture does not support blocking for results\")\n\n    def _set_done(self):\n        self._done = True\n        if self._callbacks:\n            from tornado.ioloop import IOLoop\n            loop = IOLoop.current()\n            for cb in self._callbacks:\n                loop.add_callback(cb, self)\n            self._callbacks = None\n\n    # On Python 3.3 or older, objects with a destructor part of a reference\n    # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to\n    # the PEP 442.\n    if _GC_CYCLE_FINALIZERS:\n        def __del__(self, is_finalizing=is_finalizing):\n            if is_finalizing() or not self._log_traceback:\n                # set_exception() was not called, or result() or exception()\n                # has consumed the exception\n                return\n\n            tb = traceback.format_exception(*self._exc_info)\n\n            app_log.error('Future %r exception was never retrieved: %s',\n                          self, ''.join(tb).rstrip())\n\n\nif asyncio is not None:\n    Future = asyncio.Future  # noqa\n\nif futures is None:\n    FUTURES = Future  # type: typing.Union[type, typing.Tuple[type, ...]]\nelse:\n    FUTURES = (futures.Future, Future)\n\n\ndef is_future(x):\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(object):\n    def submit(self, fn, *args, **kwargs):\n        future = Future()\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait=True):\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args, **kwargs):\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    The decorated method may be called with a ``callback`` keyword\n    argument and returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n    \"\"\"\n    def run_on_executor_decorator(fn):\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self, *args, **kwargs):\n            callback = kwargs.pop(\"callback\", None)\n            future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            if callback:\n                from tornado.ioloop import IOLoop\n                IOLoop.current().add_future(\n                    future, lambda future: callback(future.result()))\n            return future\n        return wrapper\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef return_future(f):\n    \"\"\"Decorator to make a function that returns via callback return a\n    `Future`.\n\n    This decorator was provided to ease the transition from\n    callback-oriented code to coroutines. It is not recommended for\n    new code.\n\n    The wrapped function should take a ``callback`` keyword argument\n    and invoke it with one argument when it has finished.  To signal failure,\n    the function can simply raise an exception (which will be\n    captured by the `.StackContext` and passed along to the ``Future``).\n\n    From the caller's perspective, the callback argument is optional.\n    If one is given, it will be invoked when the function is complete\n    with ``Future.result()`` as an argument.  If the function fails, the\n    callback will not be run and an exception will be raised into the\n    surrounding `.StackContext`.\n\n    If no callback is given, the caller should use the ``Future`` to\n    wait for the function to complete (perhaps by yielding it in a\n    `.gen.engine` function, or passing it to `.IOLoop.add_future`).\n\n    Usage:\n\n    .. testcode::\n\n        @return_future\n        def future_func(arg1, arg2, callback):\n            # Do stuff (possibly asynchronous)\n            callback(result)\n\n        @gen.engine\n        def caller(callback):\n            yield future_func(arg1, arg2)\n            callback()\n\n    ..\n\n    Note that ``@return_future`` and ``@gen.engine`` can be applied to the\n    same function, provided ``@return_future`` appears first.  However,\n    consider using ``@gen.coroutine`` instead of this combination.\n\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = Future()\n        callback, args, kwargs = replacer.replace(\n            lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value),\n            args, kwargs)\n\n        def handle_error(typ, value, tb):\n            future_set_exc_info(future, (typ, value, tb))\n            return True\n        exc_info = None\n        with ExceptionStackContext(handle_error):\n            try:\n                result = f(*args, **kwargs)\n                if result is not None:\n                    raise ReturnValueIgnoredError(\n                        \"@return_future should not be used with functions \"\n                        \"that return values\")\n            except:\n                exc_info = sys.exc_info()\n                raise\n        if exc_info is not None:\n            # If the initial synchronous part of f() raised an exception,\n            # go ahead and raise it to the caller directly without waiting\n            # for them to inspect the Future.\n            future.result()\n\n        # If the caller passed in a callback, schedule it to be called\n        # when the future resolves.  It is important that this happens\n        # just before we return the future, or else we risk confusing\n        # stack contexts with multiple exceptions (one here with the\n        # immediate exception, and again when the future resolves and\n        # the callback triggers its exception by calling future.result()).\n        if callback is not None:\n            def run_callback(future):\n                result = future.result()\n                if result is _NO_RESULT:\n                    callback()\n                else:\n                    callback(future.result())\n            future_add_done_callback(future, wrap(run_callback))\n        return future\n    return wrapper\n\n\ndef chain_future(a, b):\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n    def copy(future):\n        assert future is a\n        if b.done():\n            return\n        if (hasattr(a, 'exc_info') and\n                a.exc_info() is not None):\n            future_set_exc_info(b, a.exc_info())\n        elif a.exception() is not None:\n            b.set_exception(a.exception())\n        else:\n            b.set_result(a.result())\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(future, value):\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids asyncio.InvalidStateError when calling set_result() on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exc_info(future, exc_info):\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and Tornado's extensions to\n    enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if hasattr(future, 'set_exc_info'):\n        # Tornado's Future\n        future.set_exc_info(exc_info)\n    else:\n        # asyncio.Future\n        future.set_exception(exc_info[1])\n\n\ndef future_add_done_callback(future, callback):\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\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: Cannot await methods decorated with @run_on_executor - Raises TypeError

**Description**

When using the `@run_on_executor` decorator, attempting to `await` the decorated method results in a `TypeError` because the returned future is not compatible with `await` expressions.

**Example Code:**

```python
from concurrent import futures
from tornado.concurrent import run_on_executor

class Object:
    def __init__(self):
        self.executor = futures.ThreadPoolExecutor(1)

    @run_on_executor()
    def f(self):
        return 42

async def async_function():
    o = Object()
    result = await o.f()
    return result
```

**Expected Behavior:**
The `await o.f()` call should return `42` without any errors.

**Actual Behavior:**
Raises `TypeError: object Future can't be used in 'await' expression`
[/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/concurrent.py
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for working with ``Future`` objects.

``Futures`` are a pattern for concurrent programming introduced in
Python 3.2 in the `concurrent.futures` package, and also adopted (in a
slightly different form) in Python 3.4's `asyncio` package. This
package defines a ``Future`` class that is an alias for `asyncio.Future`
when available, and a compatible implementation for older versions of
Python. It also includes some utility functions for interacting with
``Future`` objects.

While this package is an important part of Tornado's internal
implementation, applications rarely need to interact with it
directly.
"""
from __future__ import absolute_import, division, print_function

import functools
import platform
import textwrap
import traceback
import sys

from tornado.log import app_log
from tornado.stack_context import ExceptionStackContext, wrap
from tornado.util import raise_exc_info, ArgReplacer, is_finalizing

try:
    from concurrent import futures
except ImportError:
    futures = None

try:
    import asyncio
except ImportError:
    asyncio = None

try:
    import typing
except ImportError:
    typing = None


# Can the garbage collector handle cycles that include __del__ methods?
# This is true in cpython beginning with version 3.4 (PEP 442).
_GC_CYCLE_FINALIZERS = (platform.python_implementation() == 'CPython' and
                        sys.version_info >= (3, 4))


class ReturnValueIgnoredError(Exception):
    pass

# This class and associated code in the future object is derived
# from the Trollius project, a backport of asyncio to Python 2.x - 3.x


class _TracebackLogger(object):
    """Helper to log a traceback upon destruction if not cleared.

    This solves a nasty problem with Futures and Tasks that have an
    exception set: if nobody asks for the exception, the exception is
    never logged.  This violates the Zen of Python: 'Errors should
    never pass silently.  Unless explicitly silenced.'

    However, we don't want to log the exception as soon as
    set_exception() is called: if the calling code is written
    properly, it will get the exception and handle it properly.  But
    we *do* want to log it if result() or exception() was never called
    -- otherwise developers waste a lot of time wondering why their
    buggy code fails silently.

    An earlier attempt added a __del__() method to the Future class
    itself, but this backfired because the presence of __del__()
    prevents garbage collection from breaking cycles.  A way out of
    this catch-22 is to avoid having a __del__() method on the Future
    class itself, but instead to have a reference to a helper object
    with a __del__() method that logs the traceback, where we ensure
    that the helper object doesn't participate in cycles, and only the
    Future has a reference to it.

    The helper object is added when set_exception() is called.  When
    the Future is collected, and the helper is present, the helper
    object is also collected, and its __del__() method will log the
    traceback.  When the Future's result() or exception() method is
    called (and a helper object is present), it removes the the helper
    object, after calling its clear() method to prevent it from
    logging.

    One downside is that we do a fair amount of work to extract the
    traceback from the exception, even when it is never logged.  It
    would seem cheaper to just store the exception object, but that
    references the traceback, which references stack frames, which may
    reference the Future, which references the _TracebackLogger, and
    then the _TracebackLogger would be included in a cycle, which is
    what we're trying to avoid!  As an optimization, we don't
    immediately format the exception; we only do the work when
    activate() is called, which call is delayed until after all the
    Future's callbacks have run.  Since usually a Future has at least
    one callback (typically set by 'yield From') and usually that
    callback extracts the callback, thereby removing the need to
    format the exception.

    PS. I don't claim credit for this solution.  I first heard of it
    in a discussion about closing files when they are collected.
    """

    __slots__ = ('exc_info', 'formatted_tb')

    def __init__(self, exc_info):
        self.exc_info = exc_info
        self.formatted_tb = None

    def activate(self):
        exc_info = self.exc_info
        if exc_info is not None:
            self.exc_info = None
            self.formatted_tb = traceback.format_exception(*exc_info)

    def clear(self):
        self.exc_info = None
        self.formatted_tb = None

    def __del__(self, is_finalizing=is_finalizing):
        if not is_finalizing() and self.formatted_tb:
            app_log.error('Future exception was never retrieved: %s',
                          ''.join(self.formatted_tb).rstrip())


class Future(object):
    """Placeholder for an asynchronous result.

    A ``Future`` encapsulates the result of an asynchronous
    operation.  In synchronous applications ``Futures`` are used
    to wait for the result from a thread or process pool; in
    Tornado they are normally used with `.IOLoop.add_future` or by
    yielding them in a `.gen.coroutine`.

    `tornado.concurrent.Future` is an alias for `asyncio.Future` when
    that package is available (Python 3.4+). Unlike
    `concurrent.futures.Future`, the ``Futures`` used by Tornado and
    `asyncio` are not thread-safe (and therefore faster for use with
    single-threaded event loops).

    In addition to ``exception`` and ``set_exception``, Tornado's
    ``Future`` implementation supports storing an ``exc_info`` triple
    to support better tracebacks on Python 2. To set an ``exc_info``
    triple, use `future_set_exc_info`, and to retrieve one, call
    `result()` (which will raise it).

    .. versionchanged:: 4.0
       `tornado.concurrent.Future` is always a thread-unsafe ``Future``
       with support for the ``exc_info`` methods.  Previously it would
       be an alias for the thread-safe `concurrent.futures.Future`
       if that package was available and fall back to the thread-unsafe
       implementation if it was not.

    .. versionchanged:: 4.1
       If a `.Future` contains an error but that error is never observed
       (by calling ``result()``, ``exception()``, or ``exc_info()``),
       a stack trace will be logged when the `.Future` is garbage collected.
       This normally indicates an error in the application, but in cases
       where it results in undesired logging it may be necessary to
       suppress the logging by ensuring that the exception is observed:
       ``f.add_done_callback(lambda f: f.exception())``.

    .. versionchanged:: 5.0

       This class was previoiusly available under the name
       ``TracebackFuture``. This name, which was deprecated since
       version 4.0, has been removed. When `asyncio` is available
       ``tornado.concurrent.Future`` is now an alias for
       `asyncio.Future`. Like `asyncio.Future`, callbacks are now
       always scheduled on the `.IOLoop` and are never run
       synchronously.

    """
    def __init__(self):
        self._done = False
        self._result = None
        self._exc_info = None

        self._log_traceback = False   # Used for Python >= 3.4
        self._tb_logger = None        # Used for Python <= 3.3

        self._callbacks = []

    # Implement the Python 3.5 Awaitable protocol if possible
    # (we can't use return and yield together until py33).
    if sys.version_info >= (3, 3):
        exec(textwrap.dedent("""
        def __await__(self):
            return (yield self)
        """))
    else:
        # Py2-compatible version for use with cython.
        def __await__(self):
            result = yield self
            # StopIteration doesn't take args before py33,
            # but Cython recognizes the args tuple.
            e = StopIteration()
            e.args = (result,)
            raise e

    def cancel(self):
        """Cancel the operation, if possible.

        Tornado ``Futures`` do not support cancellation, so this method always
        returns False.
        """
        return False

    def cancelled(self):
        """Returns True if the operation has been cancelled.

        Tornado ``Futures`` do not support cancellation, so this method
        always returns False.
        """
        return False

    def running(self):
        """Returns True if this operation is currently running."""
        return not self._done

    def done(self):
        """Returns True if the future has finished running."""
        return self._done

    def _clear_tb_log(self):
        self._log_traceback = False
        if self._tb_logger is not None:
            self._tb_logger.clear()
            self._tb_logger = None

    def result(self, timeout=None):
        """If the operation succeeded, return its result.  If it failed,
        re-raise its exception.

        This method takes a ``timeout`` argument for compatibility with
        `concurrent.futures.Future` but it is an error to call it
        before the `Future` is done, so the ``timeout`` is never used.
        """
        self._clear_tb_log()
        if self._result is not None:
            return self._result
        if self._exc_info is not None:
            try:
                raise_exc_info(self._exc_info)
            finally:
                self = None
        self._check_done()
        return self._result

    def exception(self, timeout=None):
        """If the operation raised an exception, return the `Exception`
        object.  Otherwise returns None.

        This method takes a ``timeout`` argument for compatibility with
        `concurrent.futures.Future` but it is an error to call it
        before the `Future` is done, so the ``timeout`` is never used.
        """
        self._clear_tb_log()
        if self._exc_info is not None:
            return self._exc_info[1]
        else:
            self._check_done()
            return None

    def add_done_callback(self, fn):
        """Attaches the given callback to the `Future`.

        It will be invoked with the `Future` as its argument when the Future
        has finished running and its result is available.  In Tornado
        consider using `.IOLoop.add_future` instead of calling
        `add_done_callback` directly.
        """
        if self._done:
            from tornado.ioloop import IOLoop
            IOLoop.current().add_callback(fn, self)
        else:
            self._callbacks.append(fn)

    def set_result(self, result):
        """Sets the result of a ``Future``.

        It is undefined to call any of the ``set`` methods more than once
        on the same object.
        """
        self._result = result
        self._set_done()

    def set_exception(self, exception):
        """Sets the exception of a ``Future.``"""
        self.set_exc_info(
            (exception.__class__,
             exception,
             getattr(exception, '__traceback__', None)))

    def exc_info(self):
        """Returns a tuple in the same format as `sys.exc_info` or None.

        .. versionadded:: 4.0
        """
        self._clear_tb_log()
        return self._exc_info

    def set_exc_info(self, exc_info):
        """Sets the exception information of a ``Future.``

        Preserves tracebacks on Python 2.

        .. versionadded:: 4.0
        """
        self._exc_info = exc_info
        self._log_traceback = True
        if not _GC_CYCLE_FINALIZERS:
            self._tb_logger = _TracebackLogger(exc_info)

        try:
            self._set_done()
        finally:
            # Activate the logger after all callbacks have had a
            # chance to call result() or exception().
            if self._log_traceback and self._tb_logger is not None:
                self._tb_logger.activate()
        self._exc_info = exc_info

    def _check_done(self):
        if not self._done:
            raise Exception("DummyFuture does not support blocking for results")

    def _set_done(self):
        self._done = True
        if self._callbacks:
            from tornado.ioloop import IOLoop
            loop = IOLoop.current()
            for cb in self._callbacks:
                loop.add_callback(cb, self)
            self._callbacks = None

    # On Python 3.3 or older, objects with a destructor part of a reference
    # cycle are never destroyed. It's no longer the case on Python 3.4 thanks to
    # the PEP 442.
    if _GC_CYCLE_FINALIZERS:
        def __del__(self, is_finalizing=is_finalizing):
            if is_finalizing() or not self._log_traceback:
                # set_exception() was not called, or result() or exception()
                # has consumed the exception
                return

            tb = traceback.format_exception(*self._exc_info)

            app_log.error('Future %r exception was never retrieved: %s',
                          self, ''.join(tb).rstrip())


if asyncio is not None:
    Future = asyncio.Future  # noqa

if futures is None:
    FUTURES = Future  # type: typing.Union[type, typing.Tuple[type, ...]]
else:
    FUTURES = (futures.Future, Future)


def is_future(x):
    return isinstance(x, FUTURES)


class DummyExecutor(object):
    def submit(self, fn, *args, **kwargs):
        future = Future()
        try:
            future_set_result_unless_cancelled(future, fn(*args, **kwargs))
        except Exception:
            future_set_exc_info(future, sys.exc_info())
        return future

    def shutdown(self, wait=True):
        pass


dummy_executor = DummyExecutor()


def run_on_executor(*args, **kwargs):
    """Decorator to run a synchronous method asynchronously on an executor.

    The decorated method may be called with a ``callback`` keyword
    argument and returns a future.

    The executor to be used is determined by the ``executor``
    attributes of ``self``. To use a different attribute name, pass a
    keyword argument to the decorator::

        @run_on_executor(executor='_thread_pool')
        def foo(self):
            pass

    This decorator should not be confused with the similarly-named
    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``
    when *calling* a blocking method is recommended instead of using
    this decorator when *defining* a method. If compatibility with older
    versions of Tornado is required, consider defining an executor
    and using ``executor.submit()`` at the call site.

    .. versionchanged:: 4.2
       Added keyword arguments to use alternative attributes.

    .. versionchanged:: 5.0
       Always uses the current IOLoop instead of ``self.io_loop``.
    """
    def run_on_executor_decorator(fn):
        executor = kwargs.get("executor", "executor")

        @functools.wraps(fn)
        def wrapper(self, *args, **kwargs):
            callback = kwargs.pop("callback", None)
            future = getattr(self, executor).submit(fn, self, *args, **kwargs)
            if callback:
                from tornado.ioloop import IOLoop
                IOLoop.current().add_future(
                    future, lambda future: callback(future.result()))
            return future
        return wrapper
    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator


_NO_RESULT = object()


def return_future(f):
    """Decorator to make a function that returns via callback return a
    `Future`.

    This decorator was provided to ease the transition from
    callback-oriented code to coroutines. It is not recommended for
    new code.

    The wrapped function should take a ``callback`` keyword argument
    and invoke it with one argument when it has finished.  To signal failure,
    the function can simply raise an exception (which will be
    captured by the `.StackContext` and passed along to the ``Future``).

    From the caller's perspective, the callback argument is optional.
    If one is given, it will be invoked when the function is complete
    with ``Future.result()`` as an argument.  If the function fails, the
    callback will not be run and an exception will be raised into the
    surrounding `.StackContext`.

    If no callback is given, the caller should use the ``Future`` to
    wait for the function to complete (perhaps by yielding it in a
    `.gen.engine` function, or passing it to `.IOLoop.add_future`).

    Usage:

    .. testcode::

        @return_future
        def future_func(arg1, arg2, callback):
            # Do stuff (possibly asynchronous)
            callback(result)

        @gen.engine
        def caller(callback):
            yield future_func(arg1, arg2)
            callback()

    ..

    Note that ``@return_future`` and ``@gen.engine`` can be applied to the
    same function, provided ``@return_future`` appears first.  However,
    consider using ``@gen.coroutine`` instead of this combination.

    """
    replacer = ArgReplacer(f, 'callback')

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = Future()
        callback, args, kwargs = replacer.replace(
            lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value),
            args, kwargs)

        def handle_error(typ, value, tb):
            future_set_exc_info(future, (typ, value, tb))
            return True
        exc_info = None
        with ExceptionStackContext(handle_error):
            try:
                result = f(*args, **kwargs)
                if result is not None:
                    raise ReturnValueIgnoredError(
                        "@return_future should not be used with functions "
                        "that return values")
            except:
                exc_info = sys.exc_info()
                raise
        if exc_info is not None:
            # If the initial synchronous part of f() raised an exception,
            # go ahead and raise it to the caller directly without waiting
            # for them to inspect the Future.
            future.result()

        # If the caller passed in a callback, schedule it to be called
        # when the future resolves.  It is important that this happens
        # just before we return the future, or else we risk confusing
        # stack contexts with multiple exceptions (one here with the
        # immediate exception, and again when the future resolves and
        # the callback triggers its exception by calling future.result()).
        if callback is not None:
            def run_callback(future):
                result = future.result()
                if result is _NO_RESULT:
                    callback()
                else:
                    callback(future.result())
            future_add_done_callback(future, wrap(run_callback))
        return future
    return wrapper


def chain_future(a, b):
    """Chain two futures together so that when one completes, so does the other.

    The result (success or failure) of ``a`` will be copied to ``b``, unless
    ``b`` has already been completed or cancelled by the time ``a`` finishes.

    .. versionchanged:: 5.0

       Now accepts both Tornado/asyncio `Future` objects and
       `concurrent.futures.Future`.

    """
    def copy(future):
        assert future is a
        if b.done():
            return
        if (hasattr(a, 'exc_info') and
                a.exc_info() is not None):
            future_set_exc_info(b, a.exc_info())
        elif a.exception() is not None:
            b.set_exception(a.exception())
        else:
            b.set_result(a.result())
    if isinstance(a, Future):
        future_add_done_callback(a, copy)
    else:
        # concurrent.futures.Future
        from tornado.ioloop import IOLoop
        IOLoop.current().add_future(a, copy)


def future_set_result_unless_cancelled(future, value):
    """Set the given ``value`` as the `Future`'s result, if not cancelled.

    Avoids asyncio.InvalidStateError when calling set_result() on
    a cancelled `asyncio.Future`.

    .. versionadded:: 5.0
    """
    if not future.cancelled():
        future.set_result(value)


def future_set_exc_info(future, exc_info):
    """Set the given ``exc_info`` as the `Future`'s exception.

    Understands both `asyncio.Future` and Tornado's extensions to
    enable better tracebacks on Python 2.

    .. versionadded:: 5.0
    """
    if hasattr(future, 'set_exc_info'):
        # Tornado's Future
        future.set_exc_info(exc_info)
    else:
        # asyncio.Future
        future.set_exception(exc_info[1])


def future_add_done_callback(future, callback):
    """Arrange to call ``callback`` when ``future`` is complete.

    ``callback`` is invoked with one argument, the ``future``.

    If ``future`` is already done, ``callback`` is invoked immediately.
    This may differ from the behavior of ``Future.add_done_callback``,
    which makes no such guarantee.

    .. versionadded:: 5.0
    """
    if future.done():
        callback(future)
    else:
        future.add_done_callback(callback)

```
--- 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