{
    "file_diffs": [
        {
            "old_file_content": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nFor functions that do not return ``Futures``, `Task` works with any\nfunction that takes a ``callback`` keyword argument (most Tornado functions\ncan be used in either style, although the ``Future`` style is preferred\nsince it is both shorter and provides better exception handling)::\n\n    @gen.coroutine\n    def get(self):\n        yield gen.Task(AsyncHTTPClient().fetch, \"http://example.com\")\n\nYou can also yield a list of ``Futures`` and/or ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future, TracebackFuture\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext, wrap\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        if value is not None:\n                            raise ReturnValueIgnoredError(\n                                \"@gen.engine functions cannot return values: \"\n                                \"%r\" % (value,))\n                        assert value is None\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return\n            if result is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (result,))\n            # no yield, so we're done\n    return wrapper\n\n\ndef coroutine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.  These decorators only work\n    on functions that are already asynchronous.  For\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>` methods, this\n    means that both the `tornado.web.asynchronous` and\n    `tornado.gen.coroutine` decorators must be used (for proper\n    exception handling, ``asynchronous`` should come before\n    ``gen.coroutine``).\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n        future = TracebackFuture()\n\n        if 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        def handle_exception(typ, value, tb):\n            try:\n                if runner is not None and runner.handle_exception(typ, value, tb):\n                    return True\n            except Exception:\n                typ, value, tb = sys.exc_info()\n            future.set_exc_info((typ, value, tb))\n            return True\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n                return future\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        future.set_result(value)\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return future\n            future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    Applications do not normally need to use this class, but it may be\n    subclassed to provide additional yielding behavior.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.io_loop.add_future(self.future, runner.result_callback(self.key))\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints``.\n    \"\"\"\n    def __init__(self, children):\n        self.children = []\n        for i in children:\n            if isinstance(i, Future):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return None\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n",
            "new_file_content": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nFor functions that do not return ``Futures``, `Task` works with any\nfunction that takes a ``callback`` keyword argument (most Tornado functions\ncan be used in either style, although the ``Future`` style is preferred\nsince it is both shorter and provides better exception handling)::\n\n    @gen.coroutine\n    def get(self):\n        yield gen.Task(AsyncHTTPClient().fetch, \"http://example.com\")\n\nYou can also yield a list of ``Futures`` and/or ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future, TracebackFuture\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext, wrap\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        if value is not None:\n                            raise ReturnValueIgnoredError(\n                                \"@gen.engine functions cannot return values: \"\n                                \"%r\" % (value,))\n                        assert value is None\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return\n            if result is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (result,))\n            # no yield, so we're done\n    return wrapper\n\n\ndef coroutine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.  These decorators only work\n    on functions that are already asynchronous.  For\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>` methods, this\n    means that both the `tornado.web.asynchronous` and\n    `tornado.gen.coroutine` decorators must be used (for proper\n    exception handling, ``asynchronous`` should come before\n    ``gen.coroutine``).\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n        future = TracebackFuture()\n\n        if 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        def handle_exception(typ, value, tb):\n            try:\n                if runner is not None and runner.handle_exception(typ, value, tb):\n                    return True\n            except Exception:\n                typ, value, tb = sys.exc_info()\n            future.set_exc_info((typ, value, tb))\n            return True\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n                return future\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        future.set_result(value)\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return future\n            future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    Applications do not normally need to use this class, but it may be\n    subclassed to provide additional yielding behavior.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.io_loop.add_future(self.future, runner.result_callback(self.key))\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints``.\n    \"\"\"\n    def __init__(self, children):\n        self.children = []\n        for i in children:\n            if isinstance(i, Future):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return None\n\n\n_null_yield_point = _NullYieldPoint()\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\n",
            "header": {
                "file": {
                    "path": "tornado/gen.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "938fef61",
                "new_commit_hash": "7f8de128",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/gen.py"
            },
            "plus_file": {
                "path": "b/tornado/gen.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 439,
                            "length": 6
                        },
                        "new_range": {
                            "start": 439,
                            "length": 9
                        },
                        "section": "class _NullYieldPoint(YieldPoint):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        return None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "_null_yield_point = _NullYieldPoint()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class Runner(object):",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"Internal implementation of `tornado.gen.engine`.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "statement",
                            "name": "",
                            "content": "_null_yield_point = _NullYieldPoint()",
                            "ast_type_str": "Assign",
                            "start_lineno": 442,
                            "end_lineno": 442,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 449,
                            "length": 7
                        },
                        "new_range": {
                            "start": 452,
                            "length": 7
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def __init__(self, gen, final_callback):",
                                "type": "context"
                            },
                            {
                                "content": "        self.gen = gen",
                                "type": "context"
                            },
                            {
                                "content": "        self.final_callback = final_callback",
                                "type": "context"
                            },
                            {
                                "content": "        self.yield_point = _NullYieldPoint()",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.yield_point = _null_yield_point",
                                "type": "added"
                            },
                            {
                                "content": "        self.pending_callbacks = set()",
                                "type": "context"
                            },
                            {
                                "content": "        self.results = {}",
                                "type": "context"
                            },
                            {
                                "content": "        self.running = False",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Runner.__init__",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 449,
                            "end_lineno": 458,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Runner",
                                "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 442,
                                "end_lineno": 555,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Runner",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 442,
                            "end_lineno": 555,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 505,
                            "length": 6
                        },
                        "new_range": {
                            "start": 508,
                            "length": 7
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                        yielded = self.gen.send(next)",
                                "type": "context"
                            },
                            {
                                "content": "                except (StopIteration, Return) as e:",
                                "type": "context"
                            },
                            {
                                "content": "                    self.finished = True",
                                "type": "context"
                            },
                            {
                                "content": "                    self.yield_point = _null_yield_point",
                                "type": "added"
                            },
                            {
                                "content": "                    if self.pending_callbacks and not self.had_exception:",
                                "type": "context"
                            },
                            {
                                "content": "                        # If we ran cleanly without waiting on all callbacks",
                                "type": "context"
                            },
                            {
                                "content": "                        # raise an error (really more of a warning).  If we",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Runner.run",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 485,
                            "end_lineno": 541,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Runner",
                                "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 445,
                                "end_lineno": 560,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Runner",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 445,
                            "end_lineno": 560,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 518,
                            "length": 6
                        },
                        "new_range": {
                            "start": 522,
                            "length": 7
                        },
                        "section": "class Runner(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                    return",
                                "type": "context"
                            },
                            {
                                "content": "                except Exception:",
                                "type": "context"
                            },
                            {
                                "content": "                    self.finished = True",
                                "type": "context"
                            },
                            {
                                "content": "                    self.yield_point = _null_yield_point",
                                "type": "added"
                            },
                            {
                                "content": "                    raise",
                                "type": "context"
                            },
                            {
                                "content": "                if isinstance(yielded, list):",
                                "type": "context"
                            },
                            {
                                "content": "                    yielded = Multi(yielded)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/gen.py",
                            "type": "method",
                            "name": "Runner.run",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 485,
                            "end_lineno": 541,
                            "parent": {
                                "file_name": "tornado/gen.py",
                                "type": "class",
                                "name": "Runner",
                                "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 445,
                                "end_lineno": 560,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/gen.py",
                            "type": "class",
                            "name": "Runner",
                            "content": "class Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _null_yield_point\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    self.yield_point = _null_yield_point\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 445,
                            "end_lineno": 560,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\nimport platform\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\nskipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                'Not CPython implementation')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # Task with arguments on CPython should be relased immediately after\n        # engine stop. And should not be delayed to garbage collection.\n        class Task(gen.Task):\n            \"Task class which count self instances release.\"\n            relased = 0\n            def __del__(self):\n                type(self).relased += 1\n\n        @gen.engine\n        def f():\n            yield Task(lambda _arg, callback: callback(), Task(None))\n            self.stop()\n\n        self.run_gen(f)\n        self.assertEqual(Task.relased, 2)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/gen_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "d77297db",
                "new_commit_hash": "ae2461e5",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/gen_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/gen_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 5,
                            "length": 6
                        },
                        "new_range": {
                            "start": 5,
                            "length": 7
                        },
                        "section": "import functools"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import sys",
                                "type": "context"
                            },
                            {
                                "content": "import textwrap",
                                "type": "context"
                            },
                            {
                                "content": "import time",
                                "type": "context"
                            },
                            {
                                "content": "import platform",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.concurrent import return_future",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.escape import url_escape",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "import",
                            "name": "platform",
                            "content": "import platform",
                            "ast_type_str": "Import",
                            "start_lineno": 8,
                            "end_lineno": 8,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 19,
                            "length": 6
                        },
                        "new_range": {
                            "start": 20,
                            "length": 8
                        },
                        "section": "from tornado import gen"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "skipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')",
                                "type": "context"
                            },
                            {
                                "content": "skipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',",
                                "type": "added"
                            },
                            {
                                "content": "                                'Not CPython implementation')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class GenEngineTest(AsyncTestCase):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "skipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                'Not CPython implementation')",
                            "ast_type_str": "Assign",
                            "start_lineno": 23,
                            "end_lineno": 24,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 488,
                            "length": 6
                        },
                        "new_range": {
                            "start": 491,
                            "length": 24
                        },
                        "section": "class GenEngineTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        with self.assertRaises(gen.ReturnValueIgnoredError):",
                                "type": "context"
                            },
                            {
                                "content": "            self.run_gen(f)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @skipNotCPython",
                                "type": "added"
                            },
                            {
                                "content": "    def test_task_refcounting(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # Task with arguments on CPython should be relased immediately after",
                                "type": "added"
                            },
                            {
                                "content": "        # engine stop. And should not be delayed to garbage collection.",
                                "type": "added"
                            },
                            {
                                "content": "        class Task(gen.Task):",
                                "type": "added"
                            },
                            {
                                "content": "            \"Task class which count self instances release.\"",
                                "type": "added"
                            },
                            {
                                "content": "            relased = 0",
                                "type": "added"
                            },
                            {
                                "content": "            def __del__(self):",
                                "type": "added"
                            },
                            {
                                "content": "                type(self).relased += 1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        @gen.engine",
                                "type": "added"
                            },
                            {
                                "content": "        def f():",
                                "type": "added"
                            },
                            {
                                "content": "            yield Task(lambda _arg, callback: callback(), Task(None))",
                                "type": "added"
                            },
                            {
                                "content": "            self.stop()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.run_gen(f)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(Task.relased, 2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class GenCoroutineTest(AsyncTestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def setUp(self):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "class",
                            "name": "GenEngineTest",
                            "content": "class GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # Task with arguments on CPython should be relased immediately after\n        # engine stop. And should not be delayed to garbage collection.\n        class Task(gen.Task):\n            \"Task class which count self instances release.\"\n            relased = 0\n            def __del__(self):\n                type(self).relased += 1\n\n        @gen.engine\n        def f():\n            yield Task(lambda _arg, callback: callback(), Task(None))\n            self.stop()\n\n        self.run_gen(f)\n        self.assertEqual(Task.relased, 2)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 27,
                            "end_lineno": 510,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/gen_test.py",
                            "type": "method",
                            "name": "GenEngineTest.test_task_refcounting",
                            "content": "class GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # Task with arguments on CPython should be relased immediately after\n        # engine stop. And should not be delayed to garbage collection.\n        class Task(gen.Task):\n            \"Task class which count self instances release.\"\n            relased = 0\n            def __del__(self):\n                type(self).relased += 1\n\n        @gen.engine\n        def f():\n            yield Task(lambda _arg, callback: callback(), Task(None))\n            self.stop()\n\n        self.run_gen(f)\n        self.assertEqual(Task.relased, 2)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 495,
                            "end_lineno": 510,
                            "parent": {
                                "file_name": "tornado/test/gen_test.py",
                                "type": "class",
                                "name": "GenEngineTest",
                                "content": "class GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # Task with arguments on CPython should be relased immediately after\n        # engine stop. And should not be delayed to garbage collection.\n        class Task(gen.Task):\n            \"Task class which count self instances release.\"\n            relased = 0\n            def __del__(self):\n                type(self).relased += 1\n\n        @gen.engine\n        def f():\n            yield Task(lambda _arg, callback: callback(), Task(None))\n            self.stop()\n\n        self.run_gen(f)\n        self.assertEqual(Task.relased, 2)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 27,
                                "end_lineno": 510,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f^",
    "new_commit_hash": "b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f",
    "commit_message": "Remove reference to last task and his arguments in engine to free memory.",
    "commit_date": "2013-04-28T21:35:48+04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport functools\nimport sys\nimport textwrap\nimport time\nimport platform\n\nfrom tornado.concurrent import return_future\nfrom tornado.escape import url_escape\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.log import app_log\nfrom tornado import stack_context\nfrom tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipOnTravis\nfrom tornado.web import Application, RequestHandler, asynchronous\n\nfrom tornado import gen\n\n\nskipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available')\nskipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython',\n                                'Not CPython implementation')\n\n\nclass GenEngineTest(AsyncTestCase):\n    def setUp(self):\n        super(GenEngineTest, self).setUp()\n        self.named_contexts = []\n\n    def named_context(self, name):\n        @contextlib.contextmanager\n        def context():\n            self.named_contexts.append(name)\n            try:\n                yield\n            finally:\n                self.assertEqual(self.named_contexts.pop(), name)\n        return context\n\n    def run_gen(self, f):\n        f()\n        return self.wait()\n\n    def delay_callback(self, iterations, callback, arg):\n        \"\"\"Runs callback(arg) after a number of IOLoop iterations.\"\"\"\n        if iterations == 0:\n            callback(arg)\n        else:\n            self.io_loop.add_callback(functools.partial(\n                self.delay_callback, iterations - 1, callback, arg))\n\n    @return_future\n    def async_future(self, result, callback):\n        self.io_loop.add_callback(callback, result)\n\n    def test_no_yield(self):\n        @gen.engine\n        def f():\n            self.stop()\n        self.run_gen(f)\n\n    def test_inline_cb(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))()\n            res = yield gen.Wait(\"k1\")\n            self.assertTrue(res is None)\n            self.stop()\n        self.run_gen(f)\n\n    def test_ioloop_cb(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_phase1(self):\n        @gen.engine\n        def f():\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_phase2(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n            yield gen.Wait(\"k1\")\n            1 / 0\n        self.assertRaises(ZeroDivisionError, self.run_gen, f)\n\n    def test_exception_in_task_phase1(self):\n        def fail_task(callback):\n            1 / 0\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_task_phase2(self):\n        # This is the case that requires the use of stack_context in gen.engine\n        def fail_task(callback):\n            self.io_loop.add_callback(lambda: 1 / 0)\n\n        @gen.engine\n        def f():\n            try:\n                yield gen.Task(fail_task)\n                raise Exception(\"did not get expected exception\")\n            except ZeroDivisionError:\n                self.stop()\n        self.run_gen(f)\n\n    def test_with_arg(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(42)\n            res = yield gen.Wait(\"k1\")\n            self.assertEqual(42, res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_with_arg_tuple(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback((1, 2)))((3, 4))\n            res = yield gen.Wait((1, 2))\n            self.assertEqual((3, 4), res)\n            self.stop()\n        self.run_gen(f)\n\n    def test_key_reuse(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_reuse_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.KeyReuseError, self.run_gen, f)\n\n    def test_key_mismatch(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            yield gen.Wait(\"k2\")\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_key_mismatch_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            yield gen.Wait((2, 3))\n            self.stop()\n        self.assertRaises(gen.UnknownKeyError, self.run_gen, f)\n\n    def test_leaked_callback(self):\n        @gen.engine\n        def f():\n            yield gen.Callback(\"k1\")\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_leaked_callback_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Callback((1, 2))\n            self.stop()\n        self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)\n\n    def test_parallel_callback(self):\n        @gen.engine\n        def f():\n            for k in range(3):\n                self.io_loop.add_callback((yield gen.Callback(k)))\n            yield gen.Wait(1)\n            self.io_loop.add_callback((yield gen.Callback(3)))\n            yield gen.Wait(0)\n            yield gen.Wait(3)\n            yield gen.Wait(2)\n            self.stop()\n        self.run_gen(f)\n\n    def test_bogus_yield(self):\n        @gen.engine\n        def f():\n            yield 42\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_bogus_yield_tuple(self):\n        @gen.engine\n        def f():\n            yield (1, 2)\n        self.assertRaises(gen.BadYieldError, self.run_gen, f)\n\n    def test_reuse(self):\n        @gen.engine\n        def f():\n            self.io_loop.add_callback((yield gen.Callback(0)))\n            yield gen.Wait(0)\n            self.stop()\n        self.run_gen(f)\n        self.run_gen(f)\n\n    def test_task(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop()\n        self.run_gen(f)\n\n    def test_wait_all(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield gen.WaitAll([\"k1\", \"k2\"])\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            self.stop()\n        self.run_gen(f)\n\n    def test_resume_after_exception_in_yield(self):\n        @gen.engine\n        def f():\n            try:\n                yield gen.Wait(\"k1\")\n                raise Exception(\"did not get expected exception\")\n            except gen.UnknownKeyError:\n                pass\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            self.assertEqual((yield gen.Wait(\"k2\")), \"v2\")\n            self.stop()\n        self.run_gen(f)\n\n    def test_orphaned_callback(self):\n        @gen.engine\n        def f():\n            self.orphaned_callback = yield gen.Callback(1)\n        try:\n            self.run_gen(f)\n            raise Exception(\"did not get expected exception\")\n        except gen.LeakedCallbackError:\n            pass\n        self.orphaned_callback()\n\n    def test_multi(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"k1\"))(\"v1\")\n            (yield gen.Callback(\"k2\"))(\"v2\")\n            results = yield [gen.Wait(\"k1\"), gen.Wait(\"k2\")]\n            self.assertEqual(results, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    def test_multi_delayed(self):\n        @gen.engine\n        def f():\n            # callbacks run at different times\n            responses = yield [\n                gen.Task(self.delay_callback, 3, arg=\"v1\"),\n                gen.Task(self.delay_callback, 1, arg=\"v2\"),\n            ]\n            self.assertEqual(responses, [\"v1\", \"v2\"])\n            self.stop()\n        self.run_gen(f)\n\n    @skipOnTravis\n    @gen_test\n    def test_multi_performance(self):\n        # Yielding a list used to have quadratic performance; make\n        # sure a large list stays reasonable.  On my laptop a list of\n        # 2000 used to take 1.8s, now it takes 0.12.\n        start = time.time()\n        yield [gen.Task(self.io_loop.add_callback) for i in range(2000)]\n        end = time.time()\n        self.assertLess(end - start, 1.0)\n\n    @gen_test\n    def test_future(self):\n        result = yield self.async_future(1)\n        self.assertEqual(result, 1)\n\n    @gen_test\n    def test_multi_future(self):\n        results = yield [self.async_future(1), self.async_future(2)]\n        self.assertEqual(results, [1, 2])\n\n    def test_arguments(self):\n        @gen.engine\n        def f():\n            (yield gen.Callback(\"noargs\"))()\n            self.assertEqual((yield gen.Wait(\"noargs\")), None)\n            (yield gen.Callback(\"1arg\"))(42)\n            self.assertEqual((yield gen.Wait(\"1arg\")), 42)\n\n            (yield gen.Callback(\"kwargs\"))(value=42)\n            result = yield gen.Wait(\"kwargs\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((), dict(value=42)), result)\n            self.assertEqual(dict(value=42), result.kwargs)\n\n            (yield gen.Callback(\"2args\"))(42, 43)\n            result = yield gen.Wait(\"2args\")\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((42, 43), {}), result)\n            self.assertEqual((42, 43), result.args)\n\n            def task_func(callback):\n                callback(None, error=\"foo\")\n            result = yield gen.Task(task_func)\n            self.assertTrue(isinstance(result, gen.Arguments))\n            self.assertEqual(((None,), dict(error=\"foo\")), result)\n\n            self.stop()\n        self.run_gen(f)\n\n    def test_stack_context_leak(self):\n        # regression test: repeated invocations of a gen-based\n        # function should not result in accumulated stack_contexts\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            callback()\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                yield gen.Task(inner)\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def test_stack_context_leak_exception(self):\n        # same as previous, but with a function that exits with an exception\n        @gen.engine\n        def inner(callback):\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n\n        @gen.engine\n        def outer():\n            for i in range(10):\n                try:\n                    yield gen.Task(inner)\n                except ZeroDivisionError:\n                    pass\n            stack_increase = len(stack_context._state.contexts) - initial_stack_depth\n            self.assertTrue(stack_increase <= 2)\n            self.stop()\n        initial_stack_depth = len(stack_context._state.contexts)\n        self.run_gen(outer)\n\n    def function_with_stack_context(self, callback):\n        # Technically this function should stack_context.wrap its callback\n        # upon entry.  However, it is very common for this step to be\n        # omitted.\n        def step2():\n            self.assertEqual(self.named_contexts, ['a'])\n            self.io_loop.add_callback(callback)\n\n        with stack_context.StackContext(self.named_context('a')):\n            self.io_loop.add_callback(step2)\n\n    @gen_test\n    def test_wait_transfer_stack_context(self):\n        # Wait should not pick up contexts from where callback was invoked,\n        # even if that function improperly fails to wrap its callback.\n        cb = yield gen.Callback('k1')\n        self.function_with_stack_context(cb)\n        self.assertEqual(self.named_contexts, [])\n        yield gen.Wait('k1')\n        self.assertEqual(self.named_contexts, [])\n\n    @gen_test\n    def test_task_transfer_stack_context(self):\n        yield gen.Task(self.function_with_stack_context)\n        self.assertEqual(self.named_contexts, [])\n\n    def test_raise_after_stop(self):\n        # This pattern will be used in the following tests so make sure\n        # the exception propagates as expected.\n        @gen.engine\n        def f():\n            self.stop()\n            1 / 0\n\n        with self.assertRaises(ZeroDivisionError):\n            self.run_gen(f)\n\n    def test_sync_raise_return(self):\n        # gen.Return is allowed in @gen.engine, but it may not be used\n        # to return a value.\n        @gen.engine\n        def f():\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_async_raise_return(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            self.stop(42)\n            raise gen.Return()\n\n        result = self.run_gen(f)\n        self.assertEqual(result, 42)\n\n    def test_sync_raise_return_value(self):\n        @gen.engine\n        def f():\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_sync_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_async_raise_return_value_tuple(self):\n        @gen.engine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return((1, 2))\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return 42\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    def test_return_value_tuple(self):\n        # It is an error to apply @gen.engine to a function that returns\n        # a value.\n        @gen.engine\n        def f():\n            return (1, 2)\n\n        with self.assertRaises(gen.ReturnValueIgnoredError):\n            self.run_gen(f)\n\n    @skipNotCPython\n    def test_task_refcounting(self):\n        # Task with arguments on CPython should be relased immediately after\n        # engine stop. And should not be delayed to garbage collection.\n        class Task(gen.Task):\n            \"Task class which count self instances release.\"\n            relased = 0\n            def __del__(self):\n                type(self).relased += 1\n\n        @gen.engine\n        def f():\n            yield Task(lambda _arg, callback: callback(), Task(None))\n            self.stop()\n\n        self.run_gen(f)\n        self.assertEqual(Task.relased, 2)\n\n\nclass GenCoroutineTest(AsyncTestCase):\n    def setUp(self):\n        # Stray StopIteration exceptions can lead to tests exiting prematurely,\n        # so we need explicit checks here to make sure the tests run all\n        # the way through.\n        self.finished = False\n        super(GenCoroutineTest, self).setUp()\n\n    def tearDown(self):\n        super(GenCoroutineTest, self).tearDown()\n        assert self.finished\n\n    @gen_test\n    def test_sync_gen_return(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_async_gen_return(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            raise gen.Return(42)\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return(self):\n        @gen.coroutine\n        def f():\n            return 42\n        result = yield f()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_return(self):\n        # It is a compile-time error to return a value in a generator\n        # before Python 3.3, so we must test this with exec.\n        # Flatten the real global and local namespace into our fake globals:\n        # it's all global from the perspective of f().\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return 42\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @skipBefore33\n    @gen_test\n    def test_async_early_return(self):\n        # A yield statement exists but is not executed, which means\n        # this function \"returns\" via an exception.  This exception\n        # doesn't happen before the exception handling is set up.\n        global_namespace = dict(globals(), **locals())\n        local_namespace = {}\n        exec(textwrap.dedent(\"\"\"\n        @gen.coroutine\n        def f():\n            if True:\n                return 42\n            yield gen.Task(self.io_loop.add_callback)\n        \"\"\"), global_namespace, local_namespace)\n        result = yield local_namespace['f']()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_sync_return_no_value(self):\n        @gen.coroutine\n        def f():\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_async_return_no_value(self):\n        # Without a return value we don't need python 3.3.\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            return\n        result = yield f()\n        self.assertEqual(result, None)\n        self.finished = True\n\n    @gen_test\n    def test_sync_raise(self):\n        @gen.coroutine\n        def f():\n            1 / 0\n        # The exception is raised when the future is yielded\n        # (or equivalently when its result method is called),\n        # not when the function itself is called).\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_async_raise(self):\n        @gen.coroutine\n        def f():\n            yield gen.Task(self.io_loop.add_callback)\n            1 / 0\n        future = f()\n        with self.assertRaises(ZeroDivisionError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_pass_callback(self):\n        @gen.coroutine\n        def f():\n            raise gen.Return(42)\n        result = yield gen.Task(f)\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch one exception\n        # raised by a yield point and raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_yieldpoint_exception(self):\n        # Test exception handling: a coroutine can catch an exception\n        # raised by a yield point and not raise a different one.\n        @gen.coroutine\n        def f1():\n            1 / 0\n\n        @gen.coroutine\n        def f2():\n            try:\n                yield f1()\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n    @gen_test\n    def test_replace_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and replaced.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise KeyError()\n\n        future = f2()\n        with self.assertRaises(KeyError):\n            yield future\n        self.finished = True\n\n    @gen_test\n    def test_swallow_context_exception(self):\n        # Test exception handling: exceptions thrown into the stack context\n        # can be caught and ignored.\n        @gen.coroutine\n        def f2():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            try:\n                yield gen.Task(self.io_loop.add_timeout,\n                               self.io_loop.time() + 10)\n            except ZeroDivisionError:\n                raise gen.Return(42)\n\n        result = yield f2()\n        self.assertEqual(result, 42)\n        self.finished = True\n\n\nclass GenSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.finish(\"3\")\n\n\nclass GenCoroutineUnfinishedSequenceHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        self.io_loop = self.request.connection.stream.io_loop\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        self.write(\"1\")\n        self.io_loop.add_callback((yield gen.Callback(\"k2\")))\n        yield gen.Wait(\"k2\")\n        self.write(\"2\")\n        # reuse an old key\n        self.io_loop.add_callback((yield gen.Callback(\"k1\")))\n        yield gen.Wait(\"k1\")\n        # just write, don't finish\n        self.write(\"3\")\n\n\nclass GenTaskHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        client = AsyncHTTPClient(io_loop=io_loop)\n        response = yield gen.Task(client.fetch, self.get_argument('url'))\n        response.rethrow()\n        self.finish(b\"got response: \" + response.body)\n\n\nclass GenExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenCoroutineExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.coroutine\n    def get(self):\n        # This test depends on the order of the two decorators.\n        io_loop = self.request.connection.stream.io_loop\n        yield gen.Task(io_loop.add_callback)\n        raise Exception(\"oops\")\n\n\nclass GenYieldExceptionHandler(RequestHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        io_loop = self.request.connection.stream.io_loop\n        # Test the interaction of the two stack_contexts.\n\n        def fail_task(callback):\n            io_loop.add_callback(lambda: 1 / 0)\n        try:\n            yield gen.Task(fail_task)\n            raise Exception(\"did not get expected exception\")\n        except ZeroDivisionError:\n            self.finish('ok')\n\n\nclass GenWebTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application([\n            ('/sequence', GenSequenceHandler),\n            ('/coroutine_sequence', GenCoroutineSequenceHandler),\n            ('/coroutine_unfinished_sequence',\n             GenCoroutineUnfinishedSequenceHandler),\n            ('/task', GenTaskHandler),\n            ('/exception', GenExceptionHandler),\n            ('/coroutine_exception', GenCoroutineExceptionHandler),\n            ('/yield_exception', GenYieldExceptionHandler),\n        ])\n\n    def test_sequence_handler(self):\n        response = self.fetch('/sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_sequence_handler(self):\n        response = self.fetch('/coroutine_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_coroutine_unfinished_sequence_handler(self):\n        response = self.fetch('/coroutine_unfinished_sequence')\n        self.assertEqual(response.body, b\"123\")\n\n    def test_task_handler(self):\n        response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))\n        self.assertEqual(response.body, b\"got response: 123\")\n\n    def test_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /exception\"):\n            response = self.fetch('/exception')\n        self.assertEqual(500, response.code)\n\n    def test_coroutine_exception_handler(self):\n        # Make sure we get an error and not a timeout\n        with ExpectLog(app_log, \"Uncaught exception GET /coroutine_exception\"):\n            response = self.fetch('/coroutine_exception')\n        self.assertEqual(500, response.code)\n\n    def test_yield_exception_handler(self):\n        response = self.fetch('/yield_exception')\n        self.assertEqual(response.body, b'ok')\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 781ms\nPrepared 1 package in 732ms\nInstalled 1 package in 0.81ms\n + tornado==3.1.dev2 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f)\nResolved 29 packages in 12ms\nInstalled 29 packages in 24ms\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_b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f\n.................................................................\ncollected 65 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nPASSED r2e_tests.test_1::GenEngineTest::test_task_refcounting\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg_tuple\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\n=================== 65 passed in 0.06s ===================\n",
    "new_commit_res_stderr": "ERROR:tornado.access:500 GET /coroutine_exception (127.0.0.1) 0.38ms\nERROR:tornado.access:500 GET /exception (127.0.0.1) 0.41ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f\n.................................................................\ncollected 65 items\n\n=================================== FAILURES ===================================\n__________ GenEngineTest.test_task_refcounting __________\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_b4f36e70893ccc4f7ab4c6ec63354dce70c00b2f/r2e_tests/test_1.py\", line 510, in test_task_refcounting\n    self.assertEqual(Task.relased, 2)\nAssertionError: 0 != 2\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_early_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_async_return_no_value\nPASSED r2e_tests.test_1::GenCoroutineTest::test_pass_callback\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_replace_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_context_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_swallow_yieldpoint_exception\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_gen_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_raise\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return\nPASSED r2e_tests.test_1::GenCoroutineTest::test_sync_return_no_value\nPASSED r2e_tests.test_1::GenEngineTest::test_arguments\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_async_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_bogus_yield_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_task_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase1\nPASSED r2e_tests.test_1::GenEngineTest::test_exception_phase2\nPASSED r2e_tests.test_1::GenEngineTest::test_future\nPASSED r2e_tests.test_1::GenEngineTest::test_inline_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_ioloop_cb\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch\nPASSED r2e_tests.test_1::GenEngineTest::test_key_mismatch_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_key_reuse_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_leaked_callback_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_multi\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_delayed\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_future\nPASSED r2e_tests.test_1::GenEngineTest::test_multi_performance\nPASSED r2e_tests.test_1::GenEngineTest::test_no_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_orphaned_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_parallel_callback\nPASSED r2e_tests.test_1::GenEngineTest::test_raise_after_stop\nPASSED r2e_tests.test_1::GenEngineTest::test_resume_after_exception_in_yield\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_reuse\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak\nPASSED r2e_tests.test_1::GenEngineTest::test_stack_context_leak_exception\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value\nPASSED r2e_tests.test_1::GenEngineTest::test_sync_raise_return_value_tuple\nPASSED r2e_tests.test_1::GenEngineTest::test_task\nFAILED r2e_tests.test_1::GenEngineTest::test_task_refcounting\nPASSED r2e_tests.test_1::GenEngineTest::test_task_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_all\nPASSED r2e_tests.test_1::GenEngineTest::test_wait_transfer_stack_context\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg\nPASSED r2e_tests.test_1::GenEngineTest::test_with_arg_tuple\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_coroutine_unfinished_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_exception_handler\nPASSED r2e_tests.test_1::GenWebTest::test_sequence_handler\nPASSED r2e_tests.test_1::GenWebTest::test_task_handler\nPASSED r2e_tests.test_1::GenWebTest::test_yield_exception_handler\n=================== 1 failed, 64 passed in 0.04s ===================\n",
    "old_commit_res_stderr": "ERROR:tornado.access:500 GET /coroutine_exception (127.0.0.1) 0.46ms\nERROR:tornado.access:500 GET /exception (127.0.0.1) 0.54ms\n"
}
tornado/gen.py tornado/test/gen_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Task Instances Not Released After Engine Stops, Causing Memory Leaks

**Description:**
When executing tasks with arguments, the associated `Task` instances are not released immediately after the engine stops. This results in memory not being freed as expected, potentially leading to memory leaks in long-running applications.

**Example Code:**
```python
class Task:
    released = 0

    def __del__(self):
        type(self).released += 1

def run_tasks():
    task1 = Task()
    task2 = Task()
    # Engine stops here without releasing tasks

run_tasks()
print(Task.released)  # Expected: 2, but got: 0
```

**Expected Behavior:**
After the engine stops, all `Task` instances should be released promptly. In the example above, `Task.released` should be `2`, indicating that both `task1` and `task2` have been properly garbage collected.

**Actual Behavior:**
`Task.released` remains `0`, showing that the `Task` instances are not being released after the engine stops. This prevents the memory from being freed, leading to potential memory leaks.

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

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

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` is a generator-based interface to make it easier to
work in an asynchronous environment.  Code using the ``gen`` module
is technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, the following asynchronous handler::

    class AsyncHandler(RequestHandler):
        @asynchronous
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=self.on_fetch)

        def on_fetch(self, response):
            do_something_with_response(response)
            self.render("template.html")

could be written with ``gen`` as::

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

Most asynchronous functions in Tornado return a `.Future`;
yielding this object returns its `~.Future.result`.

For functions that do not return ``Futures``, `Task` works with any
function that takes a ``callback`` keyword argument (most Tornado functions
can be used in either style, although the ``Future`` style is preferred
since it is both shorter and provides better exception handling)::

    @gen.coroutine
    def get(self):
        yield gen.Task(AsyncHTTPClient().fetch, "http://example.com")

You can also yield a list of ``Futures`` and/or ``Tasks``, which will be
started at the same time and run in parallel; a list of results will
be returned when they are all finished::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]

For more complicated interfaces, `Task` can be split into two parts:
`Callback` and `Wait`::

    class GenAsyncHandler2(RequestHandler):
        @asynchronous
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=(yield gen.Callback("key"))
            response = yield gen.Wait("key")
            do_something_with_response(response)
            self.render("template.html")

The ``key`` argument to `Callback` and `Wait` allows for multiple
asynchronous operations to be started at different times and proceed
in parallel: yield several callbacks with different keys, then wait
for them once all the async operations have started.

The result of a `Wait` or `Task` yield expression depends on how the callback
was run.  If it was called with no arguments, the result is ``None``.  If
it was called with one argument, the result is that argument.  If it was
called with more than one argument or any keyword arguments, the result
is an `Arguments` object, which is a named tuple ``(args, kwargs)``.
"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import itertools
import sys
import types

from tornado.concurrent import Future, TracebackFuture
from tornado.ioloop import IOLoop
from tornado.stack_context import ExceptionStackContext, wrap


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


def engine(func):
    """Callback-oriented decorator for asynchronous generators.

    This is an older interface; for new code that does not need to be
    compatible with versions of Tornado older than 3.0 the
    `coroutine` decorator is recommended instead.

    This decorator is similar to `coroutine`, except it does not
    return a `.Future` and the ``callback`` argument is not treated
    specially.

    In most cases, functions decorated with `engine` should take
    a ``callback`` argument and invoke it with their result when
    they are finished.  One notable exception is the
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
    which use ``self.finish()`` in place of a callback argument.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None

        def handle_exception(typ, value, tb):
            # if the function throws an exception before its first "yield"
            # (or is not a generator at all), the Runner won't exist yet.
            # However, in that case we haven't reached anything asynchronous
            # yet, so we can just let the exception propagate.
            if runner is not None:
                return runner.handle_exception(typ, value, tb)
            return False
        with ExceptionStackContext(handle_exception):
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        if value is not None:
                            raise ReturnValueIgnoredError(
                                "@gen.engine functions cannot return values: "
                                "%r" % (value,))
                        assert value is None
                    runner = Runner(result, final_callback)
                    runner.run()
                    return
            if result is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (result,))
            # no yield, so we're done
    return wrapper


def coroutine(func):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in either this decorator or `engine`.  These decorators only work
    on functions that are already asynchronous.  For
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>` methods, this
    means that both the `tornado.web.asynchronous` and
    `tornado.gen.coroutine` decorators must be used (for proper
    exception handling, ``asynchronous`` should come before
    ``gen.coroutine``).

    Coroutines may "return" by raising the special exception
    `Return(value) <Return>`.  In Python 3.3+, it is also possible for
    the function to simply use the ``return value`` statement (prior to
    Python 3.3 generators were not allowed to also return values).
    In all versions of Python a coroutine that simply wishes to exit
    early may use the ``return`` statement without a value.

    Functions with this decorator return a `.Future`.  Additionally,
    they may be called with a ``callback`` keyword argument, which
    will be invoked with the future's result when it resolves.  If the
    coroutine fails, the callback will not be run and an exception
    will be raised into the surrounding `.StackContext`.  The
    ``callback`` argument is not visible inside the decorated
    function; it is handled by the decorator itself.

    From the caller's perspective, ``@gen.coroutine`` is similar to
    the combination of ``@return_future`` and ``@gen.engine``.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None
        future = TracebackFuture()

        if 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        def handle_exception(typ, value, tb):
            try:
                if runner is not None and runner.handle_exception(typ, value, tb):
                    return True
            except Exception:
                typ, value, tb = sys.exc_info()
            future.set_exc_info((typ, value, tb))
            return True
        with ExceptionStackContext(handle_exception):
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            except Exception:
                future.set_exc_info(sys.exc_info())
                return future
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        future.set_result(value)
                    runner = Runner(result, final_callback)
                    runner.run()
                    return future
            future.set_result(result)
        return future
    return wrapper


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

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

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

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

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


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator.

    Applications do not normally need to use this class, but it may be
    subclassed to provide additional yielding behavior.
    """
    def start(self, runner):
        """Called by the runner after the generator has yielded.

        No other methods will be called on this object before ``start``.
        """
        raise NotImplementedError()

    def is_ready(self):
        """Called by the runner to determine whether to resume the generator.

        Returns a boolean; may be called more than once.
        """
        raise NotImplementedError()

    def get_result(self):
        """Returns the value to use as the result of the yield expression.

        This method will only be called once, and only after `is_ready`
        has returned true.
        """
        raise NotImplementedError()


class Callback(YieldPoint):
    """Returns a callable object that will allow a matching `Wait` to proceed.

    The key may be any value suitable for use as a dictionary key, and is
    used to match ``Callbacks`` to their corresponding ``Waits``.  The key
    must be unique among outstanding callbacks within a single run of the
    generator function, but may be reused across different runs of the same
    function (so constants generally work fine).

    The callback may be called with zero or one arguments; if an argument
    is given it will be returned by `Wait`.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner
        runner.register_callback(self.key)

    def is_ready(self):
        return True

    def get_result(self):
        return self.runner.result_callback(self.key)


class Wait(YieldPoint):
    """Returns the argument passed to the result of a previous `Callback`."""
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class WaitAll(YieldPoint):
    """Returns the results of multiple previous `Callbacks <Callback>`.

    The argument is a sequence of `Callback` keys, and the result is
    a list of results in the same order.

    `WaitAll` is equivalent to yielding a list of `Wait` objects.
    """
    def __init__(self, keys):
        self.keys = keys

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return all(self.runner.is_ready(key) for key in self.keys)

    def get_result(self):
        return [self.runner.pop_result(key) for key in self.keys]


class Task(YieldPoint):
    """Runs a single asynchronous operation.

    Takes a function (and optional additional arguments) and runs it with
    those arguments plus a ``callback`` keyword argument.  The argument passed
    to the callback is returned as the result of the yield expression.

    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique
    key generated automatically)::

        result = yield gen.Task(func, args)

        func(args, callback=(yield gen.Callback(key)))
        result = yield gen.Wait(key)
    """
    def __init__(self, func, *args, **kwargs):
        assert "callback" not in kwargs
        self.args = args
        self.kwargs = kwargs
        self.func = func

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.kwargs["callback"] = runner.result_callback(self.key)
        self.func(*self.args, **self.kwargs)

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.io_loop.add_future(self.future, runner.result_callback(self.key))

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key).result()


class Multi(YieldPoint):
    """Runs multiple asynchronous operations in parallel.

    Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of
    their responses.  It is not necessary to call `Multi` explicitly,
    since the engine will do so automatically when the generator yields
    a list of ``YieldPoints``.
    """
    def __init__(self, children):
        self.children = []
        for i in children:
            if isinstance(i, Future):
                i = YieldFuture(i)
            self.children.append(i)
        assert all(isinstance(i, YieldPoint) for i in self.children)
        self.unfinished_children = set(self.children)

    def start(self, runner):
        for i in self.children:
            i.start(runner)

    def is_ready(self):
        finished = list(itertools.takewhile(
            lambda i: i.is_ready(), self.unfinished_children))
        self.unfinished_children.difference_update(finished)
        return not self.unfinished_children

    def get_result(self):
        return [i.get_result() for i in self.children]


class _NullYieldPoint(YieldPoint):
    def start(self, runner):
        pass

    def is_ready(self):
        return True

    def get_result(self):
        return None


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

    Maintains information about pending callbacks and their results.

    ``final_callback`` is run after the generator exits.
    """
    def __init__(self, gen, final_callback):
        self.gen = gen
        self.final_callback = final_callback
        self.yield_point = _NullYieldPoint()
        self.pending_callbacks = set()
        self.results = {}
        self.running = False
        self.finished = False
        self.exc_info = None
        self.had_exception = False

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)

    def is_ready(self, key):
        """Returns true if a result is available for ``key``."""
        if key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results

    def set_result(self, key, result):
        """Sets the result for ``key`` and attempts to resume the generator."""
        self.results[key] = result
        self.run()

    def pop_result(self, key):
        """Returns the result for ``key`` and unregisters it."""
        self.pending_callbacks.remove(key)
        return self.results.pop(key)

    def run(self):
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                if self.exc_info is None:
                    try:
                        if not self.yield_point.is_ready():
                            return
                        next = self.yield_point.get_result()
                    except Exception:
                        self.exc_info = sys.exc_info()
                try:
                    if self.exc_info is not None:
                        self.had_exception = True
                        exc_info = self.exc_info
                        self.exc_info = None
                        yielded = self.gen.throw(*exc_info)
                    else:
                        yielded = self.gen.send(next)
                except (StopIteration, Return) as e:
                    self.finished = True
                    if self.pending_callbacks and not self.had_exception:
                        # If we ran cleanly without waiting on all callbacks
                        # raise an error (really more of a warning).  If we
                        # had an exception then some callbacks may have been
                        # orphaned, so skip the check in that case.
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    self.final_callback(getattr(e, 'value', None))
                    self.final_callback = None
                    return
                except Exception:
                    self.finished = True
                    raise
                if isinstance(yielded, list):
                    yielded = Multi(yielded)
                elif isinstance(yielded, Future):
                    yielded = YieldFuture(yielded)
                if isinstance(yielded, YieldPoint):
                    self.yield_point = yielded
                    try:
                        self.yield_point.start(self)
                    except Exception:
                        self.exc_info = sys.exc_info()
                else:
                    self.exc_info = (BadYieldError(
                            "yielded unknown object %r" % (yielded,)),)
        finally:
            self.running = False

    def result_callback(self, key):
        def inner(*args, **kwargs):
            if kwargs or len(args) > 1:
                result = Arguments(args, kwargs)
            elif args:
                result = args[0]
            else:
                result = None
            self.set_result(key, result)
        return wrap(inner)

    def handle_exception(self, typ, value, tb):
        if not self.running and not self.finished:
            self.exc_info = (typ, value, tb)
            self.run()
            return True
        else:
            return False

Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])

```
--- 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:** Task Instances Not Released After Engine Stops, Causing Memory Leaks

**Description:**
When executing tasks with arguments, the associated `Task` instances are not released immediately after the engine stops. This results in memory not being freed as expected, potentially leading to memory leaks in long-running applications.

**Example Code:**
```python
class Task:
    released = 0

    def __del__(self):
        type(self).released += 1

def run_tasks():
    task1 = Task()
    task2 = Task()
    # Engine stops here without releasing tasks

run_tasks()
print(Task.released)  # Expected: 2, but got: 0
```

**Expected Behavior:**
After the engine stops, all `Task` instances should be released promptly. In the example above, `Task.released` should be `2`, indicating that both `task1` and `task2` have been properly garbage collected.

**Actual Behavior:**
`Task.released` remains `0`, showing that the `Task` instances are not being released after the engine stops. This prevents the memory from being freed, leading to potential memory leaks.

[/ISSUE]
{
    "GenCoroutineTest.test_async_early_return": "PASSED",
    "GenCoroutineTest.test_async_gen_return": "PASSED",
    "GenCoroutineTest.test_async_raise": "PASSED",
    "GenCoroutineTest.test_async_return": "PASSED",
    "GenCoroutineTest.test_async_return_no_value": "PASSED",
    "GenCoroutineTest.test_pass_callback": "PASSED",
    "GenCoroutineTest.test_replace_context_exception": "PASSED",
    "GenCoroutineTest.test_replace_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_swallow_context_exception": "PASSED",
    "GenCoroutineTest.test_swallow_yieldpoint_exception": "PASSED",
    "GenCoroutineTest.test_sync_gen_return": "PASSED",
    "GenCoroutineTest.test_sync_raise": "PASSED",
    "GenCoroutineTest.test_sync_return": "PASSED",
    "GenCoroutineTest.test_sync_return_no_value": "PASSED",
    "GenEngineTest.test_arguments": "PASSED",
    "GenEngineTest.test_async_raise_return": "PASSED",
    "GenEngineTest.test_async_raise_return_value": "PASSED",
    "GenEngineTest.test_async_raise_return_value_tuple": "PASSED",
    "GenEngineTest.test_bogus_yield": "PASSED",
    "GenEngineTest.test_bogus_yield_tuple": "PASSED",
    "GenEngineTest.test_exception_in_task_phase1": "PASSED",
    "GenEngineTest.test_exception_in_task_phase2": "PASSED",
    "GenEngineTest.test_exception_in_yield": "PASSED",
    "GenEngineTest.test_exception_phase1": "PASSED",
    "GenEngineTest.test_exception_phase2": "PASSED",
    "GenEngineTest.test_future": "PASSED",
    "GenEngineTest.test_inline_cb": "PASSED",
    "GenEngineTest.test_ioloop_cb": "PASSED",
    "GenEngineTest.test_key_mismatch": "PASSED",
    "GenEngineTest.test_key_mismatch_tuple": "PASSED",
    "GenEngineTest.test_key_reuse": "PASSED",
    "GenEngineTest.test_key_reuse_tuple": "PASSED",
    "GenEngineTest.test_leaked_callback": "PASSED",
    "GenEngineTest.test_leaked_callback_tuple": "PASSED",
    "GenEngineTest.test_multi": "PASSED",
    "GenEngineTest.test_multi_delayed": "PASSED",
    "GenEngineTest.test_multi_future": "PASSED",
    "GenEngineTest.test_multi_performance": "PASSED",
    "GenEngineTest.test_no_yield": "PASSED",
    "GenEngineTest.test_orphaned_callback": "PASSED",
    "GenEngineTest.test_parallel_callback": "PASSED",
    "GenEngineTest.test_raise_after_stop": "PASSED",
    "GenEngineTest.test_resume_after_exception_in_yield": "PASSED",
    "GenEngineTest.test_return_value": "PASSED",
    "GenEngineTest.test_return_value_tuple": "PASSED",
    "GenEngineTest.test_reuse": "PASSED",
    "GenEngineTest.test_stack_context_leak": "PASSED",
    "GenEngineTest.test_stack_context_leak_exception": "PASSED",
    "GenEngineTest.test_sync_raise_return": "PASSED",
    "GenEngineTest.test_sync_raise_return_value": "PASSED",
    "GenEngineTest.test_sync_raise_return_value_tuple": "PASSED",
    "GenEngineTest.test_task": "PASSED",
    "GenEngineTest.test_task_refcounting": "PASSED",
    "GenEngineTest.test_task_transfer_stack_context": "PASSED",
    "GenEngineTest.test_wait_all": "PASSED",
    "GenEngineTest.test_wait_transfer_stack_context": "PASSED",
    "GenEngineTest.test_with_arg": "PASSED",
    "GenEngineTest.test_with_arg_tuple": "PASSED",
    "GenWebTest.test_coroutine_exception_handler": "PASSED",
    "GenWebTest.test_coroutine_sequence_handler": "PASSED",
    "GenWebTest.test_coroutine_unfinished_sequence_handler": "PASSED",
    "GenWebTest.test_exception_handler": "PASSED",
    "GenWebTest.test_sequence_handler": "PASSED",
    "GenWebTest.test_task_handler": "PASSED",
    "GenWebTest.test_yield_exception_handler": "PASSED"
}
diff --git a/tornado/gen.py b/tornado/gen.py
index 938fef61..7f8de128 100644
--- a/tornado/gen.py
+++ b/tornado/gen.py
@@ -439,6 +439,9 @@ class _NullYieldPoint(YieldPoint):
         return None
 
 
+_null_yield_point = _NullYieldPoint()
+
+
 class Runner(object):
     """Internal implementation of `tornado.gen.engine`.
 
@@ -449,7 +452,7 @@ class Runner(object):
     def __init__(self, gen, final_callback):
         self.gen = gen
         self.final_callback = final_callback
-        self.yield_point = _NullYieldPoint()
+        self.yield_point = _null_yield_point
         self.pending_callbacks = set()
         self.results = {}
         self.running = False
@@ -505,6 +508,7 @@ class Runner(object):
                         yielded = self.gen.send(next)
                 except (StopIteration, Return) as e:
                     self.finished = True
+                    self.yield_point = _null_yield_point
                     if self.pending_callbacks and not self.had_exception:
                         # If we ran cleanly without waiting on all callbacks
                         # raise an error (really more of a warning).  If we
@@ -518,6 +522,7 @@ class Runner(object):
                     return
                 except Exception:
                     self.finished = True
+                    self.yield_point = _null_yield_point
                     raise
                 if isinstance(yielded, list):
                     yielded = Multi(yielded)

{"tornado/gen.py": "\"\"\"``tornado.gen`` is a generator-based interface to make it easier to\nwork in an asynchronous environment.  Code using the ``gen`` module\nis technically asynchronous, but it is written as a single generator\ninstead of a collection of separate functions.\n\nFor example, the following asynchronous handler::\n\n    class AsyncHandler(RequestHandler):\n        @asynchronous\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=self.on_fetch)\n\n        def on_fetch(self, response):\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\ncould be written with ``gen`` as::\n\n    class GenAsyncHandler(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            response = yield http_client.fetch(\"http://example.com\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nMost asynchronous functions in Tornado return a `.Future`;\nyielding this object returns its `~.Future.result`.\n\nFor functions that do not return ``Futures``, `Task` works with any\nfunction that takes a ``callback`` keyword argument (most Tornado functions\ncan be used in either style, although the ``Future`` style is preferred\nsince it is both shorter and provides better exception handling)::\n\n    @gen.coroutine\n    def get(self):\n        yield gen.Task(AsyncHTTPClient().fetch, \"http://example.com\")\n\nYou can also yield a list of ``Futures`` and/or ``Tasks``, which will be\nstarted at the same time and run in parallel; a list of results will\nbe returned when they are all finished::\n\n    @gen.coroutine\n    def get(self):\n        http_client = AsyncHTTPClient()\n        response1, response2 = yield [http_client.fetch(url1),\n                                      http_client.fetch(url2)]\n\nFor more complicated interfaces, `Task` can be split into two parts:\n`Callback` and `Wait`::\n\n    class GenAsyncHandler2(RequestHandler):\n        @asynchronous\n        @gen.coroutine\n        def get(self):\n            http_client = AsyncHTTPClient()\n            http_client.fetch(\"http://example.com\",\n                              callback=(yield gen.Callback(\"key\"))\n            response = yield gen.Wait(\"key\")\n            do_something_with_response(response)\n            self.render(\"template.html\")\n\nThe ``key`` argument to `Callback` and `Wait` allows for multiple\nasynchronous operations to be started at different times and proceed\nin parallel: yield several callbacks with different keys, then wait\nfor them once all the async operations have started.\n\nThe result of a `Wait` or `Task` yield expression depends on how the callback\nwas run.  If it was called with no arguments, the result is ``None``.  If\nit was called with one argument, the result is that argument.  If it was\ncalled with more than one argument or any keyword arguments, the result\nis an `Arguments` object, which is a named tuple ``(args, kwargs)``.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport functools\nimport itertools\nimport sys\nimport types\n\nfrom tornado.concurrent import Future, TracebackFuture\nfrom tornado.ioloop import IOLoop\nfrom tornado.stack_context import ExceptionStackContext, wrap\n\n\nclass KeyReuseError(Exception):\n    pass\n\n\nclass UnknownKeyError(Exception):\n    pass\n\n\nclass LeakedCallbackError(Exception):\n    pass\n\n\nclass BadYieldError(Exception):\n    pass\n\n\nclass ReturnValueIgnoredError(Exception):\n    pass\n\n\ndef engine(func):\n    \"\"\"Callback-oriented decorator for asynchronous generators.\n\n    This is an older interface; for new code that does not need to be\n    compatible with versions of Tornado older than 3.0 the\n    `coroutine` decorator is recommended instead.\n\n    This decorator is similar to `coroutine`, except it does not\n    return a `.Future` and the ``callback`` argument is not treated\n    specially.\n\n    In most cases, functions decorated with `engine` should take\n    a ``callback`` argument and invoke it with their result when\n    they are finished.  One notable exception is the\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,\n    which use ``self.finish()`` in place of a callback argument.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n\n        def handle_exception(typ, value, tb):\n            # if the function throws an exception before its first \"yield\"\n            # (or is not a generator at all), the Runner won't exist yet.\n            # However, in that case we haven't reached anything asynchronous\n            # yet, so we can just let the exception propagate.\n            if runner is not None:\n                return runner.handle_exception(typ, value, tb)\n            return False\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        if value is not None:\n                            raise ReturnValueIgnoredError(\n                                \"@gen.engine functions cannot return values: \"\n                                \"%r\" % (value,))\n                        assert value is None\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return\n            if result is not None:\n                raise ReturnValueIgnoredError(\n                    \"@gen.engine functions cannot return values: %r\" %\n                    (result,))\n            # no yield, so we're done\n    return wrapper\n\n\ndef coroutine(func):\n    \"\"\"Decorator for asynchronous generators.\n\n    Any generator that yields objects from this module must be wrapped\n    in either this decorator or `engine`.  These decorators only work\n    on functions that are already asynchronous.  For\n    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>` methods, this\n    means that both the `tornado.web.asynchronous` and\n    `tornado.gen.coroutine` decorators must be used (for proper\n    exception handling, ``asynchronous`` should come before\n    ``gen.coroutine``).\n\n    Coroutines may \"return\" by raising the special exception\n    `Return(value) <Return>`.  In Python 3.3+, it is also possible for\n    the function to simply use the ``return value`` statement (prior to\n    Python 3.3 generators were not allowed to also return values).\n    In all versions of Python a coroutine that simply wishes to exit\n    early may use the ``return`` statement without a value.\n\n    Functions with this decorator return a `.Future`.  Additionally,\n    they may be called with a ``callback`` keyword argument, which\n    will be invoked with the future's result when it resolves.  If the\n    coroutine fails, the callback will not be run and an exception\n    will be raised into the surrounding `.StackContext`.  The\n    ``callback`` argument is not visible inside the decorated\n    function; it is handled by the decorator itself.\n\n    From the caller's perspective, ``@gen.coroutine`` is similar to\n    the combination of ``@return_future`` and ``@gen.engine``.\n    \"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        runner = None\n        future = TracebackFuture()\n\n        if 'callback' in kwargs:\n            callback = kwargs.pop('callback')\n            IOLoop.current().add_future(\n                future, lambda future: callback(future.result()))\n\n        def handle_exception(typ, value, tb):\n            try:\n                if runner is not None and runner.handle_exception(typ, value, tb):\n                    return True\n            except Exception:\n                typ, value, tb = sys.exc_info()\n            future.set_exc_info((typ, value, tb))\n            return True\n        with ExceptionStackContext(handle_exception):\n            try:\n                result = func(*args, **kwargs)\n            except (Return, StopIteration) as e:\n                result = getattr(e, 'value', None)\n            except Exception:\n                future.set_exc_info(sys.exc_info())\n                return future\n            else:\n                if isinstance(result, types.GeneratorType):\n                    def final_callback(value):\n                        future.set_result(value)\n                    runner = Runner(result, final_callback)\n                    runner.run()\n                    return future\n            future.set_result(result)\n        return future\n    return wrapper\n\n\nclass Return(Exception):\n    \"\"\"Special exception to return a value from a `coroutine`.\n\n    If this exception is raised, its value argument is used as the\n    result of the coroutine::\n\n        @gen.coroutine\n        def fetch_json(url):\n            response = yield AsyncHTTPClient().fetch(url)\n            raise gen.Return(json_decode(response.body))\n\n    In Python 3.3, this exception is no longer necessary: the ``return``\n    statement can be used directly to return a value (previously\n    ``yield`` and ``return`` with a value could not be combined in the\n    same function).\n\n    By analogy with the return statement, the value argument is optional,\n    but it is never necessary to ``raise gen.Return()``.  The ``return``\n    statement can be used with no arguments instead.\n    \"\"\"\n    def __init__(self, value=None):\n        super(Return, self).__init__()\n        self.value = value\n\n\nclass YieldPoint(object):\n    \"\"\"Base class for objects that may be yielded from the generator.\n\n    Applications do not normally need to use this class, but it may be\n    subclassed to provide additional yielding behavior.\n    \"\"\"\n    def start(self, runner):\n        \"\"\"Called by the runner after the generator has yielded.\n\n        No other methods will be called on this object before ``start``.\n        \"\"\"\n        raise NotImplementedError()\n\n    def is_ready(self):\n        \"\"\"Called by the runner to determine whether to resume the generator.\n\n        Returns a boolean; may be called more than once.\n        \"\"\"\n        raise NotImplementedError()\n\n    def get_result(self):\n        \"\"\"Returns the value to use as the result of the yield expression.\n\n        This method will only be called once, and only after `is_ready`\n        has returned true.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass Callback(YieldPoint):\n    \"\"\"Returns a callable object that will allow a matching `Wait` to proceed.\n\n    The key may be any value suitable for use as a dictionary key, and is\n    used to match ``Callbacks`` to their corresponding ``Waits``.  The key\n    must be unique among outstanding callbacks within a single run of the\n    generator function, but may be reused across different runs of the same\n    function (so constants generally work fine).\n\n    The callback may be called with zero or one arguments; if an argument\n    is given it will be returned by `Wait`.\n    \"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n        runner.register_callback(self.key)\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return self.runner.result_callback(self.key)\n\n\nclass Wait(YieldPoint):\n    \"\"\"Returns the argument passed to the result of a previous `Callback`.\"\"\"\n    def __init__(self, key):\n        self.key = key\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass WaitAll(YieldPoint):\n    \"\"\"Returns the results of multiple previous `Callbacks <Callback>`.\n\n    The argument is a sequence of `Callback` keys, and the result is\n    a list of results in the same order.\n\n    `WaitAll` is equivalent to yielding a list of `Wait` objects.\n    \"\"\"\n    def __init__(self, keys):\n        self.keys = keys\n\n    def start(self, runner):\n        self.runner = runner\n\n    def is_ready(self):\n        return all(self.runner.is_ready(key) for key in self.keys)\n\n    def get_result(self):\n        return [self.runner.pop_result(key) for key in self.keys]\n\n\nclass Task(YieldPoint):\n    \"\"\"Runs a single asynchronous operation.\n\n    Takes a function (and optional additional arguments) and runs it with\n    those arguments plus a ``callback`` keyword argument.  The argument passed\n    to the callback is returned as the result of the yield expression.\n\n    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique\n    key generated automatically)::\n\n        result = yield gen.Task(func, args)\n\n        func(args, callback=(yield gen.Callback(key)))\n        result = yield gen.Wait(key)\n    \"\"\"\n    def __init__(self, func, *args, **kwargs):\n        assert \"callback\" not in kwargs\n        self.args = args\n        self.kwargs = kwargs\n        self.func = func\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.kwargs[\"callback\"] = runner.result_callback(self.key)\n        self.func(*self.args, **self.kwargs)\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key)\n\n\nclass YieldFuture(YieldPoint):\n    def __init__(self, future, io_loop=None):\n        self.future = future\n        self.io_loop = io_loop or IOLoop.current()\n\n    def start(self, runner):\n        self.runner = runner\n        self.key = object()\n        runner.register_callback(self.key)\n        self.io_loop.add_future(self.future, runner.result_callback(self.key))\n\n    def is_ready(self):\n        return self.runner.is_ready(self.key)\n\n    def get_result(self):\n        return self.runner.pop_result(self.key).result()\n\n\nclass Multi(YieldPoint):\n    \"\"\"Runs multiple asynchronous operations in parallel.\n\n    Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of\n    their responses.  It is not necessary to call `Multi` explicitly,\n    since the engine will do so automatically when the generator yields\n    a list of ``YieldPoints``.\n    \"\"\"\n    def __init__(self, children):\n        self.children = []\n        for i in children:\n            if isinstance(i, Future):\n                i = YieldFuture(i)\n            self.children.append(i)\n        assert all(isinstance(i, YieldPoint) for i in self.children)\n        self.unfinished_children = set(self.children)\n\n    def start(self, runner):\n        for i in self.children:\n            i.start(runner)\n\n    def is_ready(self):\n        finished = list(itertools.takewhile(\n            lambda i: i.is_ready(), self.unfinished_children))\n        self.unfinished_children.difference_update(finished)\n        return not self.unfinished_children\n\n    def get_result(self):\n        return [i.get_result() for i in self.children]\n\n\nclass _NullYieldPoint(YieldPoint):\n    def start(self, runner):\n        pass\n\n    def is_ready(self):\n        return True\n\n    def get_result(self):\n        return None\n\n\nclass Runner(object):\n    \"\"\"Internal implementation of `tornado.gen.engine`.\n\n    Maintains information about pending callbacks and their results.\n\n    ``final_callback`` is run after the generator exits.\n    \"\"\"\n    def __init__(self, gen, final_callback):\n        self.gen = gen\n        self.final_callback = final_callback\n        self.yield_point = _NullYieldPoint()\n        self.pending_callbacks = set()\n        self.results = {}\n        self.running = False\n        self.finished = False\n        self.exc_info = None\n        self.had_exception = False\n\n    def register_callback(self, key):\n        \"\"\"Adds ``key`` to the list of callbacks.\"\"\"\n        if key in self.pending_callbacks:\n            raise KeyReuseError(\"key %r is already pending\" % (key,))\n        self.pending_callbacks.add(key)\n\n    def is_ready(self, key):\n        \"\"\"Returns true if a result is available for ``key``.\"\"\"\n        if key not in self.pending_callbacks:\n            raise UnknownKeyError(\"key %r is not pending\" % (key,))\n        return key in self.results\n\n    def set_result(self, key, result):\n        \"\"\"Sets the result for ``key`` and attempts to resume the generator.\"\"\"\n        self.results[key] = result\n        self.run()\n\n    def pop_result(self, key):\n        \"\"\"Returns the result for ``key`` and unregisters it.\"\"\"\n        self.pending_callbacks.remove(key)\n        return self.results.pop(key)\n\n    def run(self):\n        \"\"\"Starts or resumes the generator, running until it reaches a\n        yield point that is not ready.\n        \"\"\"\n        if self.running or self.finished:\n            return\n        try:\n            self.running = True\n            while True:\n                if self.exc_info is None:\n                    try:\n                        if not self.yield_point.is_ready():\n                            return\n                        next = self.yield_point.get_result()\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                try:\n                    if self.exc_info is not None:\n                        self.had_exception = True\n                        exc_info = self.exc_info\n                        self.exc_info = None\n                        yielded = self.gen.throw(*exc_info)\n                    else:\n                        yielded = self.gen.send(next)\n                except (StopIteration, Return) as e:\n                    self.finished = True\n                    if self.pending_callbacks and not self.had_exception:\n                        # If we ran cleanly without waiting on all callbacks\n                        # raise an error (really more of a warning).  If we\n                        # had an exception then some callbacks may have been\n                        # orphaned, so skip the check in that case.\n                        raise LeakedCallbackError(\n                            \"finished without waiting for callbacks %r\" %\n                            self.pending_callbacks)\n                    self.final_callback(getattr(e, 'value', None))\n                    self.final_callback = None\n                    return\n                except Exception:\n                    self.finished = True\n                    raise\n                if isinstance(yielded, list):\n                    yielded = Multi(yielded)\n                elif isinstance(yielded, Future):\n                    yielded = YieldFuture(yielded)\n                if isinstance(yielded, YieldPoint):\n                    self.yield_point = yielded\n                    try:\n                        self.yield_point.start(self)\n                    except Exception:\n                        self.exc_info = sys.exc_info()\n                else:\n                    self.exc_info = (BadYieldError(\n                            \"yielded unknown object %r\" % (yielded,)),)\n        finally:\n            self.running = False\n\n    def result_callback(self, key):\n        def inner(*args, **kwargs):\n            if kwargs or len(args) > 1:\n                result = Arguments(args, kwargs)\n            elif args:\n                result = args[0]\n            else:\n                result = None\n            self.set_result(key, result)\n        return wrap(inner)\n\n    def handle_exception(self, typ, value, tb):\n        if not self.running and not self.finished:\n            self.exc_info = (typ, value, tb)\n            self.run()\n            return True\n        else:\n            return False\n\nArguments = collections.namedtuple('Arguments', ['args', 'kwargs'])\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:** Task Instances Not Released After Engine Stops, Causing Memory Leaks

**Description:**
When executing tasks with arguments, the associated `Task` instances are not released immediately after the engine stops. This results in memory not being freed as expected, potentially leading to memory leaks in long-running applications.

**Example Code:**
```python
class Task:
    released = 0

    def __del__(self):
        type(self).released += 1

def run_tasks():
    task1 = Task()
    task2 = Task()
    # Engine stops here without releasing tasks

run_tasks()
print(Task.released)  # Expected: 2, but got: 0
```

**Expected Behavior:**
After the engine stops, all `Task` instances should be released promptly. In the example above, `Task.released` should be `2`, indicating that both `task1` and `task2` have been properly garbage collected.

**Actual Behavior:**
`Task.released` remains `0`, showing that the `Task` instances are not being released after the engine stops. This prevents the memory from being freed, leading to potential memory leaks.

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

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

--- BEGIN FILE ---
```
### tornado/gen.py
"""``tornado.gen`` is a generator-based interface to make it easier to
work in an asynchronous environment.  Code using the ``gen`` module
is technically asynchronous, but it is written as a single generator
instead of a collection of separate functions.

For example, the following asynchronous handler::

    class AsyncHandler(RequestHandler):
        @asynchronous
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=self.on_fetch)

        def on_fetch(self, response):
            do_something_with_response(response)
            self.render("template.html")

could be written with ``gen`` as::

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

Most asynchronous functions in Tornado return a `.Future`;
yielding this object returns its `~.Future.result`.

For functions that do not return ``Futures``, `Task` works with any
function that takes a ``callback`` keyword argument (most Tornado functions
can be used in either style, although the ``Future`` style is preferred
since it is both shorter and provides better exception handling)::

    @gen.coroutine
    def get(self):
        yield gen.Task(AsyncHTTPClient().fetch, "http://example.com")

You can also yield a list of ``Futures`` and/or ``Tasks``, which will be
started at the same time and run in parallel; a list of results will
be returned when they are all finished::

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response1, response2 = yield [http_client.fetch(url1),
                                      http_client.fetch(url2)]

For more complicated interfaces, `Task` can be split into two parts:
`Callback` and `Wait`::

    class GenAsyncHandler2(RequestHandler):
        @asynchronous
        @gen.coroutine
        def get(self):
            http_client = AsyncHTTPClient()
            http_client.fetch("http://example.com",
                              callback=(yield gen.Callback("key"))
            response = yield gen.Wait("key")
            do_something_with_response(response)
            self.render("template.html")

The ``key`` argument to `Callback` and `Wait` allows for multiple
asynchronous operations to be started at different times and proceed
in parallel: yield several callbacks with different keys, then wait
for them once all the async operations have started.

The result of a `Wait` or `Task` yield expression depends on how the callback
was run.  If it was called with no arguments, the result is ``None``.  If
it was called with one argument, the result is that argument.  If it was
called with more than one argument or any keyword arguments, the result
is an `Arguments` object, which is a named tuple ``(args, kwargs)``.
"""
from __future__ import absolute_import, division, print_function, with_statement

import collections
import functools
import itertools
import sys
import types

from tornado.concurrent import Future, TracebackFuture
from tornado.ioloop import IOLoop
from tornado.stack_context import ExceptionStackContext, wrap


class KeyReuseError(Exception):
    pass


class UnknownKeyError(Exception):
    pass


class LeakedCallbackError(Exception):
    pass


class BadYieldError(Exception):
    pass


class ReturnValueIgnoredError(Exception):
    pass


def engine(func):
    """Callback-oriented decorator for asynchronous generators.

    This is an older interface; for new code that does not need to be
    compatible with versions of Tornado older than 3.0 the
    `coroutine` decorator is recommended instead.

    This decorator is similar to `coroutine`, except it does not
    return a `.Future` and the ``callback`` argument is not treated
    specially.

    In most cases, functions decorated with `engine` should take
    a ``callback`` argument and invoke it with their result when
    they are finished.  One notable exception is the
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
    which use ``self.finish()`` in place of a callback argument.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None

        def handle_exception(typ, value, tb):
            # if the function throws an exception before its first "yield"
            # (or is not a generator at all), the Runner won't exist yet.
            # However, in that case we haven't reached anything asynchronous
            # yet, so we can just let the exception propagate.
            if runner is not None:
                return runner.handle_exception(typ, value, tb)
            return False
        with ExceptionStackContext(handle_exception):
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        if value is not None:
                            raise ReturnValueIgnoredError(
                                "@gen.engine functions cannot return values: "
                                "%r" % (value,))
                        assert value is None
                    runner = Runner(result, final_callback)
                    runner.run()
                    return
            if result is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (result,))
            # no yield, so we're done
    return wrapper


def coroutine(func):
    """Decorator for asynchronous generators.

    Any generator that yields objects from this module must be wrapped
    in either this decorator or `engine`.  These decorators only work
    on functions that are already asynchronous.  For
    `~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>` methods, this
    means that both the `tornado.web.asynchronous` and
    `tornado.gen.coroutine` decorators must be used (for proper
    exception handling, ``asynchronous`` should come before
    ``gen.coroutine``).

    Coroutines may "return" by raising the special exception
    `Return(value) <Return>`.  In Python 3.3+, it is also possible for
    the function to simply use the ``return value`` statement (prior to
    Python 3.3 generators were not allowed to also return values).
    In all versions of Python a coroutine that simply wishes to exit
    early may use the ``return`` statement without a value.

    Functions with this decorator return a `.Future`.  Additionally,
    they may be called with a ``callback`` keyword argument, which
    will be invoked with the future's result when it resolves.  If the
    coroutine fails, the callback will not be run and an exception
    will be raised into the surrounding `.StackContext`.  The
    ``callback`` argument is not visible inside the decorated
    function; it is handled by the decorator itself.

    From the caller's perspective, ``@gen.coroutine`` is similar to
    the combination of ``@return_future`` and ``@gen.engine``.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None
        future = TracebackFuture()

        if 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        def handle_exception(typ, value, tb):
            try:
                if runner is not None and runner.handle_exception(typ, value, tb):
                    return True
            except Exception:
                typ, value, tb = sys.exc_info()
            future.set_exc_info((typ, value, tb))
            return True
        with ExceptionStackContext(handle_exception):
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            except Exception:
                future.set_exc_info(sys.exc_info())
                return future
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        future.set_result(value)
                    runner = Runner(result, final_callback)
                    runner.run()
                    return future
            future.set_result(result)
        return future
    return wrapper


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

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

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

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

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


class YieldPoint(object):
    """Base class for objects that may be yielded from the generator.

    Applications do not normally need to use this class, but it may be
    subclassed to provide additional yielding behavior.
    """
    def start(self, runner):
        """Called by the runner after the generator has yielded.

        No other methods will be called on this object before ``start``.
        """
        raise NotImplementedError()

    def is_ready(self):
        """Called by the runner to determine whether to resume the generator.

        Returns a boolean; may be called more than once.
        """
        raise NotImplementedError()

    def get_result(self):
        """Returns the value to use as the result of the yield expression.

        This method will only be called once, and only after `is_ready`
        has returned true.
        """
        raise NotImplementedError()


class Callback(YieldPoint):
    """Returns a callable object that will allow a matching `Wait` to proceed.

    The key may be any value suitable for use as a dictionary key, and is
    used to match ``Callbacks`` to their corresponding ``Waits``.  The key
    must be unique among outstanding callbacks within a single run of the
    generator function, but may be reused across different runs of the same
    function (so constants generally work fine).

    The callback may be called with zero or one arguments; if an argument
    is given it will be returned by `Wait`.
    """
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner
        runner.register_callback(self.key)

    def is_ready(self):
        return True

    def get_result(self):
        return self.runner.result_callback(self.key)


class Wait(YieldPoint):
    """Returns the argument passed to the result of a previous `Callback`."""
    def __init__(self, key):
        self.key = key

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class WaitAll(YieldPoint):
    """Returns the results of multiple previous `Callbacks <Callback>`.

    The argument is a sequence of `Callback` keys, and the result is
    a list of results in the same order.

    `WaitAll` is equivalent to yielding a list of `Wait` objects.
    """
    def __init__(self, keys):
        self.keys = keys

    def start(self, runner):
        self.runner = runner

    def is_ready(self):
        return all(self.runner.is_ready(key) for key in self.keys)

    def get_result(self):
        return [self.runner.pop_result(key) for key in self.keys]


class Task(YieldPoint):
    """Runs a single asynchronous operation.

    Takes a function (and optional additional arguments) and runs it with
    those arguments plus a ``callback`` keyword argument.  The argument passed
    to the callback is returned as the result of the yield expression.

    A `Task` is equivalent to a `Callback`/`Wait` pair (with a unique
    key generated automatically)::

        result = yield gen.Task(func, args)

        func(args, callback=(yield gen.Callback(key)))
        result = yield gen.Wait(key)
    """
    def __init__(self, func, *args, **kwargs):
        assert "callback" not in kwargs
        self.args = args
        self.kwargs = kwargs
        self.func = func

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.kwargs["callback"] = runner.result_callback(self.key)
        self.func(*self.args, **self.kwargs)

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key)


class YieldFuture(YieldPoint):
    def __init__(self, future, io_loop=None):
        self.future = future
        self.io_loop = io_loop or IOLoop.current()

    def start(self, runner):
        self.runner = runner
        self.key = object()
        runner.register_callback(self.key)
        self.io_loop.add_future(self.future, runner.result_callback(self.key))

    def is_ready(self):
        return self.runner.is_ready(self.key)

    def get_result(self):
        return self.runner.pop_result(self.key).result()


class Multi(YieldPoint):
    """Runs multiple asynchronous operations in parallel.

    Takes a list of ``Tasks`` or other ``YieldPoints`` and returns a list of
    their responses.  It is not necessary to call `Multi` explicitly,
    since the engine will do so automatically when the generator yields
    a list of ``YieldPoints``.
    """
    def __init__(self, children):
        self.children = []
        for i in children:
            if isinstance(i, Future):
                i = YieldFuture(i)
            self.children.append(i)
        assert all(isinstance(i, YieldPoint) for i in self.children)
        self.unfinished_children = set(self.children)

    def start(self, runner):
        for i in self.children:
            i.start(runner)

    def is_ready(self):
        finished = list(itertools.takewhile(
            lambda i: i.is_ready(), self.unfinished_children))
        self.unfinished_children.difference_update(finished)
        return not self.unfinished_children

    def get_result(self):
        return [i.get_result() for i in self.children]


class _NullYieldPoint(YieldPoint):
    def start(self, runner):
        pass

    def is_ready(self):
        return True

    def get_result(self):
        return None


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

    Maintains information about pending callbacks and their results.

    ``final_callback`` is run after the generator exits.
    """
    def __init__(self, gen, final_callback):
        self.gen = gen
        self.final_callback = final_callback
        self.yield_point = _NullYieldPoint()
        self.pending_callbacks = set()
        self.results = {}
        self.running = False
        self.finished = False
        self.exc_info = None
        self.had_exception = False

    def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)

    def is_ready(self, key):
        """Returns true if a result is available for ``key``."""
        if key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results

    def set_result(self, key, result):
        """Sets the result for ``key`` and attempts to resume the generator."""
        self.results[key] = result
        self.run()

    def pop_result(self, key):
        """Returns the result for ``key`` and unregisters it."""
        self.pending_callbacks.remove(key)
        return self.results.pop(key)

    def run(self):
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                if self.exc_info is None:
                    try:
                        if not self.yield_point.is_ready():
                            return
                        next = self.yield_point.get_result()
                    except Exception:
                        self.exc_info = sys.exc_info()
                try:
                    if self.exc_info is not None:
                        self.had_exception = True
                        exc_info = self.exc_info
                        self.exc_info = None
                        yielded = self.gen.throw(*exc_info)
                    else:
                        yielded = self.gen.send(next)
                except (StopIteration, Return) as e:
                    self.finished = True
                    if self.pending_callbacks and not self.had_exception:
                        # If we ran cleanly without waiting on all callbacks
                        # raise an error (really more of a warning).  If we
                        # had an exception then some callbacks may have been
                        # orphaned, so skip the check in that case.
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    self.final_callback(getattr(e, 'value', None))
                    self.final_callback = None
                    return
                except Exception:
                    self.finished = True
                    raise
                if isinstance(yielded, list):
                    yielded = Multi(yielded)
                elif isinstance(yielded, Future):
                    yielded = YieldFuture(yielded)
                if isinstance(yielded, YieldPoint):
                    self.yield_point = yielded
                    try:
                        self.yield_point.start(self)
                    except Exception:
                        self.exc_info = sys.exc_info()
                else:
                    self.exc_info = (BadYieldError(
                            "yielded unknown object %r" % (yielded,)),)
        finally:
            self.running = False

    def result_callback(self, key):
        def inner(*args, **kwargs):
            if kwargs or len(args) > 1:
                result = Arguments(args, kwargs)
            elif args:
                result = args[0]
            else:
                result = None
            self.set_result(key, result)
        return wrap(inner)

    def handle_exception(self, typ, value, tb):
        if not self.running and not self.finished:
            self.exc_info = (typ, value, tb)
            self.run()
            return True
        else:
            return False

Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])

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