{
    "file_diffs": [
        {
            "old_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\nTornado previously provided its own ``Future`` class, but now uses\n`asyncio.Future`. This module contains utility functions for working\nwith `asyncio.Future` in a way that is backwards-compatible with\nTornado's old ``Future`` implementation.\n\nWhile this module is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\n\"\"\"\n\nimport asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\n\nfrom tornado.log import app_log\n\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\n\n\nclass ReturnValueIgnoredError(Exception):\n    # No longer used; was previously used by @return_future\n    pass\n\n\nFuture = asyncio.Future\n\nFUTURES = (futures.Future, Future)\n\n\ndef is_future(x: Any) -> bool:\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(futures.Executor):\n    def submit(\n        self, fn: Callable[..., _T], *args: Any, **kwargs: Any\n    ) -> \"futures.Future[_T]\":\n        future = futures.Future()  # type: futures.Future[_T]\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait: bool = True) -> None:\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args: Any, **kwargs: Any) -> Callable:\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    Returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n\n    .. versionchanged:: 5.1\n       Returns a `.Future` compatible with ``await`` instead of a\n       `concurrent.futures.Future`.\n\n    .. deprecated:: 5.1\n\n       The ``callback`` argument is deprecated and will be removed in\n       6.0. The decorator itself is discouraged in new code but will\n       not be removed in 6.0.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed.\n    \"\"\"\n    # Fully type-checking decorators is tricky, and this one is\n    # discouraged anyway so it doesn't have all the generic magic.\n    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:\n            async_future = Future()  # type: Future\n            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            chain_future(conc_future, async_future)\n            return async_future\n\n        return wrapper\n\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n\n    def copy(future: \"Future[_T]\") -> None:\n        assert future is a\n        if b.done():\n            return\n        if hasattr(a, \"exc_info\") and a.exc_info() is not None:  # type: ignore\n            future_set_exc_info(b, a.exc_info())  # type: ignore\n        else:\n            a_exc = a.exception()\n            if a_exc is not None:\n                b.set_exception(a_exc)\n            else:\n                b.set_result(a.result())\n\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", value: _T\n) -> None:\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exception_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n    \"\"\"Set the given ``exc`` as the `Future`'s exception.\n\n    If the Future is already canceled, logs the exception instead. If\n    this logging is not desired, the caller should explicitly check\n    the state of the Future and call ``Future.set_exception`` instead of\n    this wrapper.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 6.0\n\n    \"\"\"\n    if not future.cancelled():\n        future.set_exception(exc)\n    else:\n        app_log.error(\"Exception after Future was cancelled\", exc_info=exc)\n\n\ndef future_set_exc_info(\n    future: \"Union[futures.Future[_T], Future[_T]]\",\n    exc_info: Tuple[\n        Optional[type], Optional[BaseException], Optional[types.TracebackType]\n    ],\n) -> None:\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and the extensions in older\n    versions of Tornado to enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n\n    .. versionchanged:: 6.0\n\n       If the future is already cancelled, this function is a no-op.\n       (previously ``asyncio.InvalidStateError`` would be raised)\n\n    \"\"\"\n    if exc_info[1] is None:\n        raise Exception(\"future_set_exc_info called with no exception\")\n    future_set_exception_unless_cancelled(future, exc_info[1])\n\n\n@typing.overload\ndef future_add_done_callback(\n    future: \"futures.Future[_T]\", callback: Callable[[\"futures.Future[_T]\"], None]\n) -> None:\n    pass\n\n\n@typing.overload  # noqa: F811\ndef future_add_done_callback(\n    future: \"Future[_T]\", callback: Callable[[\"Future[_T]\"], None]\n) -> None:\n    pass\n\n\ndef future_add_done_callback(  # noqa: F811\n    future: \"Union[futures.Future[_T], Future[_T]]\", callback: Callable[..., None]\n) -> None:\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\n",
            "new_file_content": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\nTornado previously provided its own ``Future`` class, but now uses\n`asyncio.Future`. This module contains utility functions for working\nwith `asyncio.Future` in a way that is backwards-compatible with\nTornado's old ``Future`` implementation.\n\nWhile this module is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\n\"\"\"\n\nimport asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\n\nfrom tornado.log import app_log\n\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\n\n\nclass ReturnValueIgnoredError(Exception):\n    # No longer used; was previously used by @return_future\n    pass\n\n\nFuture = asyncio.Future\n\nFUTURES = (futures.Future, Future)\n\n\ndef is_future(x: Any) -> bool:\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(futures.Executor):\n    def submit(\n        self, fn: Callable[..., _T], *args: Any, **kwargs: Any\n    ) -> \"futures.Future[_T]\":\n        future = futures.Future()  # type: futures.Future[_T]\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait: bool = True) -> None:\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args: Any, **kwargs: Any) -> Callable:\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    Returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n\n    .. versionchanged:: 5.1\n       Returns a `.Future` compatible with ``await`` instead of a\n       `concurrent.futures.Future`.\n\n    .. deprecated:: 5.1\n\n       The ``callback`` argument is deprecated and will be removed in\n       6.0. The decorator itself is discouraged in new code but will\n       not be removed in 6.0.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed.\n    \"\"\"\n    # Fully type-checking decorators is tricky, and this one is\n    # discouraged anyway so it doesn't have all the generic magic.\n    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:\n            async_future = Future()  # type: Future\n            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            chain_future(conc_future, async_future)\n            return async_future\n\n        return wrapper\n\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n\n    def copy(a: \"Future[_T]\") -> None:\n        if b.done():\n            return\n        if hasattr(a, \"exc_info\") and a.exc_info() is not None:  # type: ignore\n            future_set_exc_info(b, a.exc_info())  # type: ignore\n        else:\n            a_exc = a.exception()\n            if a_exc is not None:\n                b.set_exception(a_exc)\n            else:\n                b.set_result(a.result())\n\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", value: _T\n) -> None:\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exception_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n    \"\"\"Set the given ``exc`` as the `Future`'s exception.\n\n    If the Future is already canceled, logs the exception instead. If\n    this logging is not desired, the caller should explicitly check\n    the state of the Future and call ``Future.set_exception`` instead of\n    this wrapper.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 6.0\n\n    \"\"\"\n    if not future.cancelled():\n        future.set_exception(exc)\n    else:\n        app_log.error(\"Exception after Future was cancelled\", exc_info=exc)\n\n\ndef future_set_exc_info(\n    future: \"Union[futures.Future[_T], Future[_T]]\",\n    exc_info: Tuple[\n        Optional[type], Optional[BaseException], Optional[types.TracebackType]\n    ],\n) -> None:\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and the extensions in older\n    versions of Tornado to enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n\n    .. versionchanged:: 6.0\n\n       If the future is already cancelled, this function is a no-op.\n       (previously ``asyncio.InvalidStateError`` would be raised)\n\n    \"\"\"\n    if exc_info[1] is None:\n        raise Exception(\"future_set_exc_info called with no exception\")\n    future_set_exception_unless_cancelled(future, exc_info[1])\n\n\n@typing.overload\ndef future_add_done_callback(\n    future: \"futures.Future[_T]\", callback: Callable[[\"futures.Future[_T]\"], None]\n) -> None:\n    pass\n\n\n@typing.overload  # noqa: F811\ndef future_add_done_callback(\n    future: \"Future[_T]\", callback: Callable[[\"Future[_T]\"], None]\n) -> None:\n    pass\n\n\ndef future_add_done_callback(  # noqa: F811\n    future: \"Union[futures.Future[_T], Future[_T]]\", callback: Callable[..., None]\n) -> None:\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\n",
            "header": {
                "file": {
                    "path": "tornado/concurrent.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "6e05346b",
                "new_commit_hash": "f0bbf623",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/concurrent.py"
            },
            "plus_file": {
                "path": "b/tornado/concurrent.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 150,
                            "length": 8
                        },
                        "new_range": {
                            "start": 150,
                            "length": 7
                        },
                        "section": "def chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def copy(future: \"Future[_T]\") -> None:",
                                "type": "deleted"
                            },
                            {
                                "content": "        assert future is a",
                                "type": "deleted"
                            },
                            {
                                "content": "    def copy(a: \"Future[_T]\") -> None:",
                                "type": "added"
                            },
                            {
                                "content": "        if b.done():",
                                "type": "context"
                            },
                            {
                                "content": "            return",
                                "type": "context"
                            },
                            {
                                "content": "        if hasattr(a, \"exc_info\") and a.exc_info() is not None:  # type: ignore",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/concurrent.py",
                            "type": "function",
                            "name": "chain_future",
                            "content": "def chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n\n    def copy(future: \"Future[_T]\") -> None:\n        assert future is a\n        if b.done():\n            return\n        if hasattr(a, \"exc_info\") and a.exc_info() is not None:  # type: ignore\n            future_set_exc_info(b, a.exc_info())  # type: ignore\n        else:\n            a_exc = a.exception()\n            if a_exc is not None:\n                b.set_exception(a_exc)\n            else:\n                b.set_result(a.result())\n\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n\n        IOLoop.current().add_future(a, copy)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 140,
                            "end_lineno": 172,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a\nslightly different interface. The `.IOLoop` interface is now provided primarily\nfor backwards compatibility; new code should generally use the `asyncio` event\nloop interface directly. The `IOLoop.current` class method provides the\n`IOLoop` instance corresponding to the running `asyncio` event loop.\n\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\nimport warnings\nfrom inspect import isawaitable\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List, Set  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = [\"deadline\", \"callback\", \"tdeadline\"]\n\n    def __init__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds when\n    ``callback_time`` is a float. Note that the timeout is given in\n    milliseconds, while most other time-related functions in Tornado use\n    seconds. ``callback_time`` may alternatively be given as a\n    `datetime.timedelta` object.\n\n    If ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n\n    .. versionchanged:: 6.2\n       If the ``callback`` argument is a coroutine, and a callback runs for\n       longer than ``callback_time``, subsequent invocations will be skipped.\n       Previously this was only true for regular functions, not coroutines,\n       which were \"fire-and-forget\" for `PeriodicCallback`.\n\n       The ``callback_time`` argument now accepts `datetime.timedelta` objects,\n       in addition to the previous numeric milliseconds.\n    \"\"\"\n\n    def __init__(\n        self,\n        callback: Callable[[], Optional[Awaitable]],\n        callback_time: Union[datetime.timedelta, float],\n        jitter: float = 0,\n    ) -> None:\n        self.callback = callback\n        if isinstance(callback_time, datetime.timedelta):\n            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)\n        else:\n            if callback_time <= 0:\n                raise ValueError(\"Periodic callback must have a positive callback_time\")\n            self.callback_time = callback_time\n        self.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self) -> None:\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    async def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            val = self.callback()\n            if val is not None and isawaitable(val):\n                await val\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\n",
            "new_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a\nslightly different interface. The `.IOLoop` interface is now provided primarily\nfor backwards compatibility; new code should generally use the `asyncio` event\nloop interface directly. The `IOLoop.current` class method provides the\n`IOLoop` instance corresponding to the running `asyncio` event loop.\n\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\nimport warnings\nfrom inspect import isawaitable\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List, Set  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, f))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(future, lambda f: self.add_callback(callback, f))\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = [\"deadline\", \"callback\", \"tdeadline\"]\n\n    def __init__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds when\n    ``callback_time`` is a float. Note that the timeout is given in\n    milliseconds, while most other time-related functions in Tornado use\n    seconds. ``callback_time`` may alternatively be given as a\n    `datetime.timedelta` object.\n\n    If ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n\n    .. versionchanged:: 6.2\n       If the ``callback`` argument is a coroutine, and a callback runs for\n       longer than ``callback_time``, subsequent invocations will be skipped.\n       Previously this was only true for regular functions, not coroutines,\n       which were \"fire-and-forget\" for `PeriodicCallback`.\n\n       The ``callback_time`` argument now accepts `datetime.timedelta` objects,\n       in addition to the previous numeric milliseconds.\n    \"\"\"\n\n    def __init__(\n        self,\n        callback: Callable[[], Optional[Awaitable]],\n        callback_time: Union[datetime.timedelta, float],\n        jitter: float = 0,\n    ) -> None:\n        self.callback = callback\n        if isinstance(callback_time, datetime.timedelta):\n            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)\n        else:\n            if callback_time <= 0:\n                raise ValueError(\"Periodic callback must have a positive callback_time\")\n            self.callback_time = callback_time\n        self.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self) -> None:\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    async def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            val = self.callback()\n            if val is not None and isawaitable(val):\n                await val\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\n",
            "header": {
                "file": {
                    "path": "tornado/ioloop.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "cdfb4a63",
                "new_commit_hash": "3fb1359a",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/ioloop.py"
            },
            "plus_file": {
                "path": "b/tornado/ioloop.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 696,
                            "length": 15
                        },
                        "new_range": {
                            "start": 696,
                            "length": 13
                        },
                        "section": "class IOLoop(Configurable):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            # the error logging (i.e. it goes to tornado.log.app_log",
                                "type": "context"
                            },
                            {
                                "content": "            # instead of asyncio's log).",
                                "type": "context"
                            },
                            {
                                "content": "            future.add_done_callback(",
                                "type": "context"
                            },
                            {
                                "content": "                lambda f: self._run_callback(functools.partial(callback, future))",
                                "type": "deleted"
                            },
                            {
                                "content": "                lambda f: self._run_callback(functools.partial(callback, f))",
                                "type": "added"
                            },
                            {
                                "content": "            )",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            assert is_future(future)",
                                "type": "context"
                            },
                            {
                                "content": "            # For concurrent futures, we use self.add_callback, so",
                                "type": "context"
                            },
                            {
                                "content": "            # it's fine if future_add_done_callback inlines that call.",
                                "type": "context"
                            },
                            {
                                "content": "            future_add_done_callback(",
                                "type": "deleted"
                            },
                            {
                                "content": "                future, lambda f: self.add_callback(callback, future)",
                                "type": "deleted"
                            },
                            {
                                "content": "            )",
                                "type": "deleted"
                            },
                            {
                                "content": "            future_add_done_callback(future, lambda f: self.add_callback(callback, f))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def run_in_executor(",
                                "type": "context"
                            },
                            {
                                "content": "        self,",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "class",
                            "name": "IOLoop",
                            "content": "class IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 72,
                            "end_lineno": 824,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "method",
                            "name": "IOLoop.add_future",
                            "content": "class IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 674,
                            "end_lineno": 707,
                            "parent": {
                                "file_name": "tornado/ioloop.py",
                                "type": "class",
                                "name": "IOLoop",
                                "content": "class IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 72,
                                "end_lineno": 824,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Test script to find circular references.\n\nCircular references are not leaks per se, because they will eventually\nbe GC'd. However, on CPython, they prevent the reference-counting fast\npath from being used and instead rely on the slower full GC. This\nincreases memory footprint and CPU overhead, so we try to eliminate\ncircular references created by normal operation.\n\"\"\"\n\nimport asyncio\nimport contextlib\nimport gc\nimport io\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\n\nimport tornado\nfrom tornado import web, gen, httpclient\n\n\ndef find_circular_references(garbage):\n    \"\"\"Find circular references in a list of objects.\n\n    The garbage list contains objects that participate in a cycle,\n    but also the larger set of objects kept alive by that cycle.\n    This function finds subsets of those objects that make up\n    the cycle(s).\n    \"\"\"\n\n    def inner(level):\n        for item in level:\n            item_id = id(item)\n            if item_id not in garbage_ids:\n                continue\n            if item_id in visited_ids:\n                continue\n            if item_id in stack_ids:\n                candidate = stack[stack.index(item) :]\n                candidate.append(item)\n                found.append(candidate)\n                continue\n\n            stack.append(item)\n            stack_ids.add(item_id)\n            inner(gc.get_referents(item))\n            stack.pop()\n            stack_ids.remove(item_id)\n            visited_ids.add(item_id)\n\n    found: typing.List[object] = []\n    stack = []\n    stack_ids = set()\n    garbage_ids = set(map(id, garbage))\n    visited_ids = set()\n\n    inner(garbage)\n    return found\n\n\n@contextlib.contextmanager\ndef assert_no_cycle_garbage():\n    \"\"\"Raise AssertionError if the wrapped code creates garbage with cycles.\"\"\"\n    gc.disable()\n    gc.collect()\n    gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_SAVEALL)\n    yield\n    try:\n        # We have DEBUG_STATS on which causes gc.collect to write to stderr.\n        # Capture the output instead of spamming the logs on passing runs.\n        f = io.StringIO()\n        old_stderr = sys.stderr\n        sys.stderr = f\n        try:\n            gc.collect()\n        finally:\n            sys.stderr = old_stderr\n        garbage = gc.garbage[:]\n        # Must clear gc.garbage (the same object, not just replacing it with a\n        # new list) to avoid warnings at shutdown.\n        gc.garbage[:] = []\n        if len(garbage) == 0:\n            return\n        for circular in find_circular_references(garbage):\n            f.write(\"\\n==========\\n Circular \\n==========\")\n            for item in circular:\n                f.write(f\"\\n    {repr(item)}\")\n            for item in circular:\n                if isinstance(item, types.FrameType):\n                    f.write(f\"\\nLocals: {item.f_locals}\")\n                    f.write(f\"\\nTraceback: {repr(item)}\")\n                    traceback.print_stack(item)\n        del garbage\n        raise AssertionError(f.getvalue())\n    finally:\n        gc.set_debug(0)\n        gc.enable()\n\n\nclass CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n",
            "new_file_content": "\"\"\"Test script to find circular references.\n\nCircular references are not leaks per se, because they will eventually\nbe GC'd. However, on CPython, they prevent the reference-counting fast\npath from being used and instead rely on the slower full GC. This\nincreases memory footprint and CPU overhead, so we try to eliminate\ncircular references created by normal operation.\n\"\"\"\n\nimport asyncio\nimport contextlib\nimport gc\nimport io\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\n\nimport tornado\nfrom tornado import web, gen, httpclient\n\n\ndef find_circular_references(garbage):\n    \"\"\"Find circular references in a list of objects.\n\n    The garbage list contains objects that participate in a cycle,\n    but also the larger set of objects kept alive by that cycle.\n    This function finds subsets of those objects that make up\n    the cycle(s).\n    \"\"\"\n\n    def inner(level):\n        for item in level:\n            item_id = id(item)\n            if item_id not in garbage_ids:\n                continue\n            if item_id in visited_ids:\n                continue\n            if item_id in stack_ids:\n                candidate = stack[stack.index(item) :]\n                candidate.append(item)\n                found.append(candidate)\n                continue\n\n            stack.append(item)\n            stack_ids.add(item_id)\n            inner(gc.get_referents(item))\n            stack.pop()\n            stack_ids.remove(item_id)\n            visited_ids.add(item_id)\n\n    found: typing.List[object] = []\n    stack = []\n    stack_ids = set()\n    garbage_ids = set(map(id, garbage))\n    visited_ids = set()\n\n    inner(garbage)\n    return found\n\n\n@contextlib.contextmanager\ndef assert_no_cycle_garbage():\n    \"\"\"Raise AssertionError if the wrapped code creates garbage with cycles.\"\"\"\n    gc.disable()\n    gc.collect()\n    gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_SAVEALL)\n    yield\n    try:\n        # We have DEBUG_STATS on which causes gc.collect to write to stderr.\n        # Capture the output instead of spamming the logs on passing runs.\n        f = io.StringIO()\n        old_stderr = sys.stderr\n        sys.stderr = f\n        try:\n            gc.collect()\n        finally:\n            sys.stderr = old_stderr\n        garbage = gc.garbage[:]\n        # Must clear gc.garbage (the same object, not just replacing it with a\n        # new list) to avoid warnings at shutdown.\n        gc.garbage[:] = []\n        if len(garbage) == 0:\n            return\n        for circular in find_circular_references(garbage):\n            f.write(\"\\n==========\\n Circular \\n==========\")\n            for item in circular:\n                f.write(f\"\\n    {repr(item)}\")\n            for item in circular:\n                if isinstance(item, types.FrameType):\n                    f.write(f\"\\nLocals: {item.f_locals}\")\n                    f.write(f\"\\nTraceback: {repr(item)}\")\n                    traceback.print_stack(item)\n        del garbage\n        raise AssertionError(f.getvalue())\n    finally:\n        gc.set_debug(0)\n        gc.enable()\n\n\nclass CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_run_on_executor(self):\n        # From https://github.com/tornadoweb/tornado/issues/2620\n        #\n        # When this test was introduced it found cycles in IOLoop.add_future\n        # and tornado.concurrent.chain_future.\n        import concurrent.futures\n\n        thread_pool = concurrent.futures.ThreadPoolExecutor(1)\n\n        class Factory(object):\n            executor = thread_pool\n\n            @tornado.concurrent.run_on_executor\n            def run(self):\n                return None\n\n        factory = Factory()\n\n        async def main():\n            # The cycle is not reported on the first call. It's not clear why.\n            for i in range(2):\n                await factory.run()\n\n        with assert_no_cycle_garbage():\n            asyncio.run(main())\n",
            "header": {
                "file": {
                    "path": "tornado/test/circlerefs_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "2502c5fb",
                "new_commit_hash": "3908588c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/circlerefs_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/circlerefs_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 181,
                            "length": 3
                        },
                        "new_range": {
                            "start": 181,
                            "length": 29
                        },
                        "section": "class CircleRefsTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                self.write(\"ok\\n\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        asyncio.run(self.run_handler(Handler))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_run_on_executor(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # From https://github.com/tornadoweb/tornado/issues/2620",
                                "type": "added"
                            },
                            {
                                "content": "        #",
                                "type": "added"
                            },
                            {
                                "content": "        # When this test was introduced it found cycles in IOLoop.add_future",
                                "type": "added"
                            },
                            {
                                "content": "        # and tornado.concurrent.chain_future.",
                                "type": "added"
                            },
                            {
                                "content": "        import concurrent.futures",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        thread_pool = concurrent.futures.ThreadPoolExecutor(1)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        class Factory(object):",
                                "type": "added"
                            },
                            {
                                "content": "            executor = thread_pool",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            @tornado.concurrent.run_on_executor",
                                "type": "added"
                            },
                            {
                                "content": "            def run(self):",
                                "type": "added"
                            },
                            {
                                "content": "                return None",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        factory = Factory()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        async def main():",
                                "type": "added"
                            },
                            {
                                "content": "            # The cycle is not reported on the first call. It's not clear why.",
                                "type": "added"
                            },
                            {
                                "content": "            for i in range(2):",
                                "type": "added"
                            },
                            {
                                "content": "                await factory.run()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        with assert_no_cycle_garbage():",
                                "type": "added"
                            },
                            {
                                "content": "            asyncio.run(main())",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/circlerefs_test.py",
                            "type": "class",
                            "name": "CircleRefsTest",
                            "content": "class CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_run_on_executor(self):\n        # From https://github.com/tornadoweb/tornado/issues/2620\n        #\n        # When this test was introduced it found cycles in IOLoop.add_future\n        # and tornado.concurrent.chain_future.\n        import concurrent.futures\n\n        thread_pool = concurrent.futures.ThreadPoolExecutor(1)\n\n        class Factory(object):\n            executor = thread_pool\n\n            @tornado.concurrent.run_on_executor\n            def run(self):\n                return None\n\n        factory = Factory()\n\n        async def main():\n            # The cycle is not reported on the first call. It's not clear why.\n            for i in range(2):\n                await factory.run()\n\n        with assert_no_cycle_garbage():\n            asyncio.run(main())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 102,
                            "end_lineno": 209,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/circlerefs_test.py",
                            "type": "method",
                            "name": "CircleRefsTest.test_run_on_executor",
                            "content": "class CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_run_on_executor(self):\n        # From https://github.com/tornadoweb/tornado/issues/2620\n        #\n        # When this test was introduced it found cycles in IOLoop.add_future\n        # and tornado.concurrent.chain_future.\n        import concurrent.futures\n\n        thread_pool = concurrent.futures.ThreadPoolExecutor(1)\n\n        class Factory(object):\n            executor = thread_pool\n\n            @tornado.concurrent.run_on_executor\n            def run(self):\n                return None\n\n        factory = Factory()\n\n        async def main():\n            # The cycle is not reported on the first call. It's not clear why.\n            for i in range(2):\n                await factory.run()\n\n        with assert_no_cycle_garbage():\n            asyncio.run(main())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 185,
                            "end_lineno": 209,
                            "parent": {
                                "file_name": "tornado/test/circlerefs_test.py",
                                "type": "class",
                                "name": "CircleRefsTest",
                                "content": "class CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_run_on_executor(self):\n        # From https://github.com/tornadoweb/tornado/issues/2620\n        #\n        # When this test was introduced it found cycles in IOLoop.add_future\n        # and tornado.concurrent.chain_future.\n        import concurrent.futures\n\n        thread_pool = concurrent.futures.ThreadPoolExecutor(1)\n\n        class Factory(object):\n            executor = thread_pool\n\n            @tornado.concurrent.run_on_executor\n            def run(self):\n                return None\n\n        factory = Factory()\n\n        async def main():\n            # The cycle is not reported on the first call. It's not clear why.\n            for i in range(2):\n                await factory.run()\n\n        with assert_no_cycle_garbage():\n            asyncio.run(main())",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 102,
                                "end_lineno": 209,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "1d5fc98018bd1d742b1608634bfb57f6e3d990f0^",
    "new_commit_hash": "1d5fc98018bd1d742b1608634bfb57f6e3d990f0",
    "commit_message": "ioloop,concurrent: Fix reference cycles\n\nIn a few places we were referring to a future via a closure instead\nof using the reference passed as an argument to the callback.  This\nsometimes causes a reference cycle that can slow GC. This commit\nadds a test which covers two of the cases (chain_future and the\nconcurrent.future branch of add_future) while the third was found by\ninspecting other calls to add_done_callback for obvious instances of\nthis pattern.\n\nFixes #2620",
    "commit_date": "2023-08-21T23:03:39-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "1d5fc98018bd1d742b1608634bfb57f6e3d990f0",
    "test_file_codes": [
        "\"\"\"Test script to find circular references.\n\nCircular references are not leaks per se, because they will eventually\nbe GC'd. However, on CPython, they prevent the reference-counting fast\npath from being used and instead rely on the slower full GC. This\nincreases memory footprint and CPU overhead, so we try to eliminate\ncircular references created by normal operation.\n\"\"\"\n\nimport asyncio\nimport contextlib\nimport gc\nimport io\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\n\nimport tornado\nfrom tornado import web, gen, httpclient\n\n\ndef find_circular_references(garbage):\n    \"\"\"Find circular references in a list of objects.\n\n    The garbage list contains objects that participate in a cycle,\n    but also the larger set of objects kept alive by that cycle.\n    This function finds subsets of those objects that make up\n    the cycle(s).\n    \"\"\"\n\n    def inner(level):\n        for item in level:\n            item_id = id(item)\n            if item_id not in garbage_ids:\n                continue\n            if item_id in visited_ids:\n                continue\n            if item_id in stack_ids:\n                candidate = stack[stack.index(item) :]\n                candidate.append(item)\n                found.append(candidate)\n                continue\n\n            stack.append(item)\n            stack_ids.add(item_id)\n            inner(gc.get_referents(item))\n            stack.pop()\n            stack_ids.remove(item_id)\n            visited_ids.add(item_id)\n\n    found: typing.List[object] = []\n    stack = []\n    stack_ids = set()\n    garbage_ids = set(map(id, garbage))\n    visited_ids = set()\n\n    inner(garbage)\n    return found\n\n\n@contextlib.contextmanager\ndef assert_no_cycle_garbage():\n    \"\"\"Raise AssertionError if the wrapped code creates garbage with cycles.\"\"\"\n    gc.disable()\n    gc.collect()\n    gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_SAVEALL)\n    yield\n    try:\n        # We have DEBUG_STATS on which causes gc.collect to write to stderr.\n        # Capture the output instead of spamming the logs on passing runs.\n        f = io.StringIO()\n        old_stderr = sys.stderr\n        sys.stderr = f\n        try:\n            gc.collect()\n        finally:\n            sys.stderr = old_stderr\n        garbage = gc.garbage[:]\n        # Must clear gc.garbage (the same object, not just replacing it with a\n        # new list) to avoid warnings at shutdown.\n        gc.garbage[:] = []\n        if len(garbage) == 0:\n            return\n        for circular in find_circular_references(garbage):\n            f.write(\"\\n==========\\n Circular \\n==========\")\n            for item in circular:\n                f.write(f\"\\n    {repr(item)}\")\n            for item in circular:\n                if isinstance(item, types.FrameType):\n                    f.write(f\"\\nLocals: {item.f_locals}\")\n                    f.write(f\"\\nTraceback: {repr(item)}\")\n                    traceback.print_stack(item)\n        del garbage\n        raise AssertionError(f.getvalue())\n    finally:\n        gc.set_debug(0)\n        gc.enable()\n\n\nclass CircleRefsTest(unittest.TestCase):\n    def test_known_leak(self):\n        # Construct a known leak scenario to make sure the test harness works.\n        class C(object):\n            def __init__(self, name):\n                self.name = name\n                self.a: typing.Optional[C] = None\n                self.b: typing.Optional[C] = None\n                self.c: typing.Optional[C] = None\n\n            def __repr__(self):\n                return f\"name={self.name}\"\n\n        with self.assertRaises(AssertionError) as cm:\n            with assert_no_cycle_garbage():\n                # a and b form a reference cycle. c is not part of the cycle,\n                # but it cannot be GC'd while a and b are alive.\n                a = C(\"a\")\n                b = C(\"b\")\n                c = C(\"c\")\n                a.b = b\n                a.c = c\n                b.a = a\n                b.c = c\n                del a, b\n        self.assertIn(\"Circular\", str(cm.exception))\n        self.assertIn(\"name=a\", str(cm.exception))\n        self.assertIn(\"name=b\", str(cm.exception))\n        self.assertNotIn(\"name=c\", str(cm.exception))\n\n    async def run_handler(self, handler_class):\n        app = web.Application(\n            [\n                (r\"/\", handler_class),\n            ]\n        )\n        socket, port = tornado.testing.bind_unused_port()\n        server = tornado.httpserver.HTTPServer(app)\n        server.add_socket(socket)\n\n        client = httpclient.AsyncHTTPClient()\n        with assert_no_cycle_garbage():\n            # Only the fetch (and the corresponding server-side handler)\n            # are being tested for cycles. In particular, the Application\n            # object has internal cycles (as of this writing) which we don't\n            # care to fix since in real world usage the Application object\n            # is effectively a global singleton.\n            await client.fetch(f\"http://127.0.0.1:{port}/\")\n        client.close()\n        server.stop()\n        socket.close()\n\n    def test_sync_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_finish_exception_handler(self):\n        class Handler(web.RequestHandler):\n            def get(self):\n                raise web.Finish(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_coro_handler(self):\n        class Handler(web.RequestHandler):\n            @gen.coroutine\n            def get(self):\n                yield asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_async_handler(self):\n        class Handler(web.RequestHandler):\n            async def get(self):\n                await asyncio.sleep(0.01)\n                self.write(\"ok\\n\")\n\n        asyncio.run(self.run_handler(Handler))\n\n    def test_run_on_executor(self):\n        # From https://github.com/tornadoweb/tornado/issues/2620\n        #\n        # When this test was introduced it found cycles in IOLoop.add_future\n        # and tornado.concurrent.chain_future.\n        import concurrent.futures\n\n        thread_pool = concurrent.futures.ThreadPoolExecutor(1)\n\n        class Factory(object):\n            executor = thread_pool\n\n            @tornado.concurrent.run_on_executor\n            def run(self):\n                return None\n\n        factory = Factory()\n\n        async def main():\n            # The cycle is not reported on the first call. It's not clear why.\n            for i in range(2):\n                await factory.run()\n\n        with assert_no_cycle_garbage():\n            asyncio.run(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 849ms\nPrepared 1 package in 1.02s\nInstalled 1 package in 1ms\n + tornado==6.4.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_1d5fc98018bd1d742b1608634bfb57f6e3d990f0)\nResolved 29 packages in 9ms\nInstalled 29 packages in 119ms\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": 1,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_1d5fc98018bd1d742b1608634bfb57f6e3d990f0\n......\ncollected 6 items\n\n=================================== FAILURES ===================================\n__________ CircleRefsTest.test_known_leak __________\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_1d5fc98018bd1d742b1608634bfb57f6e3d990f0/r2e_tests/test_1.py\", line 130, in test_known_leak\n    self.assertNotIn(\"name=c\", str(cm.exception))\nAssertionError: 'name=c' unexpectedly found in \"gc: collecting generation 2...\\ngc: objects in each generation: 7 0 23408\\ngc: objects in permanent generation: 0\\ngc: done, 4 unreachable, 0 uncollectable, 0.0033s elapsed\\n\\n==========\\n Circular \\n==========\\n    name=a\\n    {'name': 'a', 'a': None, 'b': name=b, 'c': name=c}\\n    name=b\\n    {'name': 'b', 'a': name=a, 'b': None, 'c': name=c}\\n    name=a\"\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::CircleRefsTest::test_async_handler\nPASSED r2e_tests.test_1::CircleRefsTest::test_coro_handler\nPASSED r2e_tests.test_1::CircleRefsTest::test_finish_exception_handler\nFAILED r2e_tests.test_1::CircleRefsTest::test_known_leak\nPASSED r2e_tests.test_1::CircleRefsTest::test_run_on_executor\nPASSED r2e_tests.test_1::CircleRefsTest::test_sync_handler\n=================== 1 failed, 5 passed in 0.10s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_1d5fc98018bd1d742b1608634bfb57f6e3d990f0\n......\ncollected 6 items\n\n=================================== FAILURES ===================================\n__________ CircleRefsTest.test_known_leak __________\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_1d5fc98018bd1d742b1608634bfb57f6e3d990f0/r2e_tests/test_1.py\", line 130, in test_known_leak\n    self.assertNotIn(\"name=c\", str(cm.exception))\nAssertionError: 'name=c' unexpectedly found in \"gc: collecting generation 2...\\ngc: objects in each generation: 7 0 23408\\ngc: objects in permanent generation: 0\\ngc: done, 4 unreachable, 0 uncollectable, 0.0028s elapsed\\n\\n==========\\n Circular \\n==========\\n    name=a\\n    {'name': 'a', 'a': None, 'b': name=b, 'c': name=c}\\n    name=b\\n    {'name': 'b', 'a': name=a, 'b': None, 'c': name=c}\\n    name=a\"\n__________ CircleRefsTest.test_run_on_executor __________\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_1d5fc98018bd1d742b1608634bfb57f6e3d990f0/r2e_tests/test_1.py\", line 209, in test_run_on_executor\n    asyncio.run(main())\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/contextlib.py\", line 126, in __exit__\n    next(self.gen)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_1d5fc98018bd1d742b1608634bfb57f6e3d990f0/r2e_tests/test_1.py\", line 96, in assert_no_cycle_garbage\n    raise AssertionError(f.getvalue())\nAssertionError: gc: collecting generation 2...\ngc: objects in each generation: 77 0 23439\ngc: objects in permanent generation: 0\ngc: done, 22 unreachable, 0 uncollectable, 0.0028s elapsed\n\n==========\n Circular \n==========\n    <Future at 0x751fda33b070 state=finished returned NoneType>\n    {'_condition': <Condition(<unlocked _thread.RLock object owner=0 count=0 at 0x751fda33b090>, 0)>, '_state': 'FINISHED', '_result': None, '_exception': None, '_waiters': [], '_done_callbacks': [<function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>]}\n    [<function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>]\n    <function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>\n    (<cell at 0x751fda331ee0: function object at 0x751fda3e1e50>, <cell at 0x751fda331f10: Future object at 0x751fda33b070>, <cell at 0x751fda331ca0: AsyncIOMainLoop object at 0x751fda2e9bb0>)\n    <cell at 0x751fda331f10: Future object at 0x751fda33b070>\n    <Future at 0x751fda33b070 state=finished returned NoneType>\n==========\n Circular \n==========\n    <Future at 0x751fda33b070 state=finished returned NoneType>\n    {'_condition': <Condition(<unlocked _thread.RLock object owner=0 count=0 at 0x751fda33b090>, 0)>, '_state': 'FINISHED', '_result': None, '_exception': None, '_waiters': [], '_done_callbacks': [<function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>]}\n    [<function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>]\n    <function IOLoop.add_future.<locals>.<lambda> at 0x751fda35cc10>\n    (<cell at 0x751fda331ee0: function object at 0x751fda3e1e50>, <cell at 0x751fda331f10: Future object at 0x751fda33b070>, <cell at 0x751fda331ca0: AsyncIOMainLoop object at 0x751fda2e9bb0>)\n    <cell at 0x751fda331ee0: function object at 0x751fda3e1e50>\n    <function chain_future.<locals>.copy at 0x751fda3e1e50>\n    (<cell at 0x751fda331a00: Future object at 0x751fda33b070>, <cell at 0x751fda331a30: _asyncio.Future object at 0x751fda72d7c0>)\n    <cell at 0x751fda331a00: Future object at 0x751fda33b070>\n    <Future at 0x751fda33b070 state=finished returned NoneType>\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::CircleRefsTest::test_async_handler\nPASSED r2e_tests.test_1::CircleRefsTest::test_coro_handler\nPASSED r2e_tests.test_1::CircleRefsTest::test_finish_exception_handler\nFAILED r2e_tests.test_1::CircleRefsTest::test_known_leak\nFAILED r2e_tests.test_1::CircleRefsTest::test_run_on_executor\nPASSED r2e_tests.test_1::CircleRefsTest::test_sync_handler\n=================== 2 failed, 4 passed in 0.08s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/concurrent.py tornado/ioloop.py tornado/test/circlerefs_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Reference Cycles Created by Callback Closures in IOLoop.add_future

**Description:**
When adding a callback to a future using a lambda that captures the future instance, a reference cycle is created. This cycle prevents the garbage collector from reclaiming the memory promptly, potentially leading to memory leaks and slower garbage collection.

**Example Code:**
```python
from tornado.ioloop import IOLoop
from tornado.concurrent import Future

def callback(fut):
    pass

loop = IOLoop.current()
future = Future()
future.add_done_callback(lambda f: callback(future))
loop.run_sync(lambda: future.set_result(None))
```

**Expected Behavior:**
After the future is completed and the callback is executed, there should be no reference cycles involving the future and the callback. The garbage collector should be able to reclaim the memory without delays.

**Actual Behavior:**
Using a lambda that captures the `future` creates a reference cycle between the future and the callback. This prevents the garbage collector from promptly reclaiming the memory, leading to potential memory leaks and degraded performance over time.

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

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

--- BEGIN FILE ---
```
### tornado/concurrent.py
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for working with ``Future`` objects.

Tornado previously provided its own ``Future`` class, but now uses
`asyncio.Future`. This module contains utility functions for working
with `asyncio.Future` in a way that is backwards-compatible with
Tornado's old ``Future`` implementation.

While this module is an important part of Tornado's internal
implementation, applications rarely need to interact with it
directly.

"""

import asyncio
from concurrent import futures
import functools
import sys
import types

from tornado.log import app_log

import typing
from typing import Any, Callable, Optional, Tuple, Union

_T = typing.TypeVar("_T")


class ReturnValueIgnoredError(Exception):
    # No longer used; was previously used by @return_future
    pass


Future = asyncio.Future

FUTURES = (futures.Future, Future)


def is_future(x: Any) -> bool:
    return isinstance(x, FUTURES)


class DummyExecutor(futures.Executor):
    def submit(
        self, fn: Callable[..., _T], *args: Any, **kwargs: Any
    ) -> "futures.Future[_T]":
        future = futures.Future()  # type: futures.Future[_T]
        try:
            future_set_result_unless_cancelled(future, fn(*args, **kwargs))
        except Exception:
            future_set_exc_info(future, sys.exc_info())
        return future

    def shutdown(self, wait: bool = True) -> None:
        pass


dummy_executor = DummyExecutor()


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

    Returns a future.

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

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

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

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

    .. versionchanged:: 5.0
       Always uses the current IOLoop instead of ``self.io_loop``.

    .. versionchanged:: 5.1
       Returns a `.Future` compatible with ``await`` instead of a
       `concurrent.futures.Future`.

    .. deprecated:: 5.1

       The ``callback`` argument is deprecated and will be removed in
       6.0. The decorator itself is discouraged in new code but will
       not be removed in 6.0.

    .. versionchanged:: 6.0

       The ``callback`` argument was removed.
    """
    # Fully type-checking decorators is tricky, and this one is
    # discouraged anyway so it doesn't have all the generic magic.
    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:
        executor = kwargs.get("executor", "executor")

        @functools.wraps(fn)
        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:
            async_future = Future()  # type: Future
            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)
            chain_future(conc_future, async_future)
            return async_future

        return wrapper

    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator


_NO_RESULT = object()


def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
    """Chain two futures together so that when one completes, so does the other.

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

    .. versionchanged:: 5.0

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

    """

    def copy(future: "Future[_T]") -> None:
        assert future is a
        if b.done():
            return
        if hasattr(a, "exc_info") and a.exc_info() is not None:  # type: ignore
            future_set_exc_info(b, a.exc_info())  # type: ignore
        else:
            a_exc = a.exception()
            if a_exc is not None:
                b.set_exception(a_exc)
            else:
                b.set_result(a.result())

    if isinstance(a, Future):
        future_add_done_callback(a, copy)
    else:
        # concurrent.futures.Future
        from tornado.ioloop import IOLoop

        IOLoop.current().add_future(a, copy)


def future_set_result_unless_cancelled(
    future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
    """Set the given ``value`` as the `Future`'s result, if not cancelled.

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

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


def future_set_exception_unless_cancelled(
    future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
    """Set the given ``exc`` as the `Future`'s exception.

    If the Future is already canceled, logs the exception instead. If
    this logging is not desired, the caller should explicitly check
    the state of the Future and call ``Future.set_exception`` instead of
    this wrapper.

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

    .. versionadded:: 6.0

    """
    if not future.cancelled():
        future.set_exception(exc)
    else:
        app_log.error("Exception after Future was cancelled", exc_info=exc)


def future_set_exc_info(
    future: "Union[futures.Future[_T], Future[_T]]",
    exc_info: Tuple[
        Optional[type], Optional[BaseException], Optional[types.TracebackType]
    ],
) -> None:
    """Set the given ``exc_info`` as the `Future`'s exception.

    Understands both `asyncio.Future` and the extensions in older
    versions of Tornado to enable better tracebacks on Python 2.

    .. versionadded:: 5.0

    .. versionchanged:: 6.0

       If the future is already cancelled, this function is a no-op.
       (previously ``asyncio.InvalidStateError`` would be raised)

    """
    if exc_info[1] is None:
        raise Exception("future_set_exc_info called with no exception")
    future_set_exception_unless_cancelled(future, exc_info[1])


@typing.overload
def future_add_done_callback(
    future: "futures.Future[_T]", callback: Callable[["futures.Future[_T]"], None]
) -> None:
    pass


@typing.overload  # noqa: F811
def future_add_done_callback(
    future: "Future[_T]", callback: Callable[["Future[_T]"], None]
) -> None:
    pass


def future_add_done_callback(  # noqa: F811
    future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None]
) -> None:
    """Arrange to call ``callback`` when ``future`` is complete.

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

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

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


### tornado/ioloop.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""An I/O event loop for non-blocking sockets.

In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a
slightly different interface. The `.IOLoop` interface is now provided primarily
for backwards compatibility; new code should generally use the `asyncio` event
loop interface directly. The `IOLoop.current` class method provides the
`IOLoop` instance corresponding to the running `asyncio` event loop.

"""

import asyncio
import concurrent.futures
import datetime
import functools
import numbers
import os
import sys
import time
import math
import random
import warnings
from inspect import isawaitable

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
)
from tornado.log import app_log
from tornado.util import Configurable, TimeoutError, import_object

import typing
from typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable

if typing.TYPE_CHECKING:
    from typing import Dict, List, Set  # noqa: F401

    from typing_extensions import Protocol
else:
    Protocol = object


class _Selectable(Protocol):
    def fileno(self) -> int:
        pass

    def close(self) -> None:
        pass


_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)


class IOLoop(Configurable):
    """An I/O event loop.

    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.

    Example usage for a simple TCP server:

    .. testcode::

        import asyncio
        import errno
        import functools
        import socket

        import tornado
        from tornado.iostream import IOStream

        async def handle_connection(connection, address):
            stream = IOStream(connection)
            message = await stream.read_until_close()
            print("message from client:", message.decode().strip())

        def connection_ready(sock, fd, events):
            while True:
                try:
                    connection, address = sock.accept()
                except BlockingIOError:
                    return
                connection.setblocking(0)
                io_loop = tornado.ioloop.IOLoop.current()
                io_loop.spawn_callback(handle_connection, connection, address)

        async def main():
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setblocking(0)
            sock.bind(("", 8888))
            sock.listen(128)

            io_loop = tornado.ioloop.IOLoop.current()
            callback = functools.partial(connection_ready, sock)
            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
            await asyncio.Event().wait()

        if __name__ == "__main__":
            asyncio.run(main())

    .. testoutput::
       :hide:

    Most applications should not attempt to construct an `IOLoop` directly,
    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.
    In some cases, such as in test frameworks when initializing an `IOLoop`
    to be run in a secondary thread, it may be appropriate to construct
    an `IOLoop` with ``IOLoop(make_current=False)``.

    In general, an `IOLoop` cannot survive a fork or be shared across processes
    in any way. When multiple processes are being used, each process should
    create its own `IOLoop`, which also implies that any objects which depend on
    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child
    processes. As a guideline, anything that starts processes (including the
    `tornado.process` and `multiprocessing` modules) should do so as early as
    possible, ideally the first thing the application does after loading its
    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.

    .. versionchanged:: 4.2
       Added the ``make_current`` keyword argument to the `IOLoop`
       constructor.

    .. versionchanged:: 5.0

       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method
       cannot be used on Python 3 except to redundantly specify the `asyncio`
       event loop.

    .. versionchanged:: 6.3
       ``make_current=True`` is now the default when creating an IOLoop -
       previously the default was to make the event loop current if there wasn't
       already a current one.
    """

    # These constants were originally based on constants from the epoll module.
    NONE = 0
    READ = 0x001
    WRITE = 0x004
    ERROR = 0x018

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]

    # Maintain a set of all pending tasks to follow the warning in the docs
    # of asyncio.create_tasks:
    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task
    # This ensures that all pending tasks have a strong reference so they
    # will not be garbage collected before they are finished.
    # (Thus avoiding "task was destroyed but it is pending" warnings)
    # An analogous change has been proposed in cpython for 3.13:
    # https://github.com/python/cpython/issues/91887
    # If that change is accepted, this can eventually be removed.
    # If it is not, we will consider the rationale and may remove this.
    _pending_tasks = set()  # type: Set[Future]

    @classmethod
    def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        from tornado.platform.asyncio import BaseAsyncIOLoop

        if isinstance(impl, str):
            impl = import_object(impl)
        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
            raise RuntimeError("only AsyncIOLoop is allowed when asyncio is available")
        super(IOLoop, cls).configure(impl, **kwargs)

    @staticmethod
    def instance() -> "IOLoop":
        """Deprecated alias for `IOLoop.current()`.

        .. versionchanged:: 5.0

           Previously, this method returned a global singleton
           `IOLoop`, in contrast with the per-thread `IOLoop` returned
           by `current()`. In nearly all cases the two were the same
           (when they differed, it was generally used from non-Tornado
           threads to communicate back to the main thread's `IOLoop`).
           This distinction is not present in `asyncio`, so in order
           to facilitate integration with that package `instance()`
           was changed to be an alias to `current()`. Applications
           using the cross-thread communications aspect of
           `instance()` should instead set their own global variable
           to point to the `IOLoop` they want to use.

        .. deprecated:: 5.0
        """
        return IOLoop.current()

    def install(self) -> None:
        """Deprecated alias for `make_current()`.

        .. versionchanged:: 5.0

           Previously, this method would set this `IOLoop` as the
           global singleton used by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`, `install()`
           is an alias for `make_current()`.

        .. deprecated:: 5.0
        """
        self.make_current()

    @staticmethod
    def clear_instance() -> None:
        """Deprecated alias for `clear_current()`.

        .. versionchanged:: 5.0

           Previously, this method would clear the `IOLoop` used as
           the global singleton by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`,
           `clear_instance()` is an alias for `clear_current()`.

        .. deprecated:: 5.0

        """
        IOLoop.clear_current()

    @typing.overload
    @staticmethod
    def current() -> "IOLoop":
        pass

    @typing.overload
    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        pass

    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        """Returns the current thread's `IOLoop`.

        If an `IOLoop` is currently running or has been marked as
        current by `make_current`, returns that instance.  If there is
        no current `IOLoop` and ``instance`` is true, creates one.

        .. versionchanged:: 4.1
           Added ``instance`` argument to control the fallback to
           `IOLoop.instance()`.
        .. versionchanged:: 5.0
           On Python 3, control of the current `IOLoop` is delegated
           to `asyncio`, with this and other methods as pass-through accessors.
           The ``instance`` argument now controls whether an `IOLoop`
           is created automatically when there is none, instead of
           whether we fall back to `IOLoop.instance()` (which is now
           an alias for this method). ``instance=False`` is deprecated,
           since even if we do not create an `IOLoop`, this method
           may initialize the asyncio loop.

        .. deprecated:: 6.2
           It is deprecated to call ``IOLoop.current()`` when no `asyncio`
           event loop is running.
        """
        try:
            loop = asyncio.get_event_loop()
        except RuntimeError:
            if not instance:
                return None
            # Create a new asyncio event loop for this thread.
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

        try:
            return IOLoop._ioloop_for_asyncio[loop]
        except KeyError:
            if instance:
                from tornado.platform.asyncio import AsyncIOMainLoop

                current = AsyncIOMainLoop()  # type: Optional[IOLoop]
            else:
                current = None
        return current

    def make_current(self) -> None:
        """Makes this the `IOLoop` for the current thread.

        An `IOLoop` automatically becomes current for its thread
        when it is started, but it is sometimes useful to call
        `make_current` explicitly before starting the `IOLoop`,
        so that code run at startup time can find the right
        instance.

        .. versionchanged:: 4.1
           An `IOLoop` created while there is no current `IOLoop`
           will automatically become current.

        .. versionchanged:: 5.0
           This method also sets the current `asyncio` event loop.

        .. deprecated:: 6.2
           Setting and clearing the current event loop through Tornado is
           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.
        """
        warnings.warn(
            "make_current is deprecated; start the event loop first",
            DeprecationWarning,
            stacklevel=2,
        )
        self._make_current()

    def _make_current(self) -> None:
        # The asyncio event loops override this method.
        raise NotImplementedError()

    @staticmethod
    def clear_current() -> None:
        """Clears the `IOLoop` for the current thread.

        Intended primarily for use by test frameworks in between tests.

        .. versionchanged:: 5.0
           This method also clears the current `asyncio` event loop.
        .. deprecated:: 6.2
        """
        warnings.warn(
            "clear_current is deprecated",
            DeprecationWarning,
            stacklevel=2,
        )
        IOLoop._clear_current()

    @staticmethod
    def _clear_current() -> None:
        old = IOLoop.current(instance=False)
        if old is not None:
            old._clear_current_hook()

    def _clear_current_hook(self) -> None:
        """Instance method called when an IOLoop ceases to be current.

        May be overridden by subclasses as a counterpart to make_current.
        """
        pass

    @classmethod
    def configurable_base(cls) -> Type[Configurable]:
        return IOLoop

    @classmethod
    def configurable_default(cls) -> Type[Configurable]:
        from tornado.platform.asyncio import AsyncIOLoop

        return AsyncIOLoop

    def initialize(self, make_current: bool = True) -> None:
        if make_current:
            self._make_current()

    def close(self, all_fds: bool = False) -> None:
        """Closes the `IOLoop`, freeing any resources used.

        If ``all_fds`` is true, all file descriptors registered on the
        IOLoop will be closed (not just the ones created by the
        `IOLoop` itself).

        Many applications will only use a single `IOLoop` that runs for the
        entire lifetime of the process.  In that case closing the `IOLoop`
        is not necessary since everything will be cleaned up when the
        process exits.  `IOLoop.close` is provided mainly for scenarios
        such as unit tests, which create and destroy a large number of
        ``IOLoops``.

        An `IOLoop` must be completely stopped before it can be closed.  This
        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must
        be allowed to return before attempting to call `IOLoop.close()`.
        Therefore the call to `close` will usually appear just after
        the call to `start` rather than near the call to `stop`.

        .. versionchanged:: 3.1
           If the `IOLoop` implementation supports non-integer objects
           for "file descriptors", those objects will have their
           ``close`` method when ``all_fds`` is true.
        """
        raise NotImplementedError()

    @typing.overload
    def add_handler(
        self, fd: int, handler: Callable[[int, int], None], events: int
    ) -> None:
        pass

    @typing.overload  # noqa: F811
    def add_handler(
        self, fd: _S, handler: Callable[[_S, int], None], events: int
    ) -> None:
        pass

    def add_handler(  # noqa: F811
        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
    ) -> None:
        """Registers the given handler to receive the given events for ``fd``.

        The ``fd`` argument may either be an integer file descriptor or
        a file-like object with a ``fileno()`` and ``close()`` method.

        The ``events`` argument is a bitwise or of the constants
        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.

        When an event occurs, ``handler(fd, events)`` will be run.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:
        """Changes the events we listen for ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def remove_handler(self, fd: Union[int, _Selectable]) -> None:
        """Stop listening for events on ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def start(self) -> None:
        """Starts the I/O loop.

        The loop will run until one of the callbacks calls `stop()`, which
        will make the loop stop after the current event iteration completes.
        """
        raise NotImplementedError()

    def stop(self) -> None:
        """Stop the I/O loop.

        If the event loop is not currently running, the next call to `start()`
        will return immediately.

        Note that even after `stop` has been called, the `IOLoop` is not
        completely stopped until `IOLoop.start` has also returned.
        Some work that was scheduled before the call to `stop` may still
        be run before the `IOLoop` shuts down.
        """
        raise NotImplementedError()

    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either an awaitable object or
        ``None``. If the function returns an awaitable object, the
        `IOLoop` will run until the awaitable is resolved (and
        `run_sync()` will return the awaitable's result). If it raises
        an exception, the `IOLoop` will stop and the exception will be
        re-raised to the caller.

        The keyword-only argument ``timeout`` may be used to set
        a maximum duration for the function.  If the timeout expires,
        a `asyncio.TimeoutError` is raised.

        This method is useful to allow asynchronous calls in a
        ``main()`` function::

            async def main():
                # do stuff...

            if __name__ == '__main__':
                IOLoop.current().run_sync(main)

        .. versionchanged:: 4.3
           Returning a non-``None``, non-awaitable value is now an error.

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.

        .. versionchanged:: 6.2
           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.
        """
        future_cell = [None]  # type: List[Optional[Future]]

        def run() -> None:
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded

                    result = convert_yielded(result)
            except Exception:
                fut = Future()  # type: Future[Any]
                future_cell[0] = fut
                future_set_exc_info(fut, sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    fut = Future()
                    future_cell[0] = fut
                    fut.set_result(result)
            assert future_cell[0] is not None
            self.add_future(future_cell[0], lambda future: self.stop())

        self.add_callback(run)
        if timeout is not None:

            def timeout_callback() -> None:
                # If we can cancel the future, do so and wait on it. If not,
                # Just stop the loop and return with the task still pending.
                # (If we neither cancel nor wait for the task, a warning
                # will be logged).
                assert future_cell[0] is not None
                if not future_cell[0].cancel():
                    self.stop()

            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
        self.start()
        if timeout is not None:
            self.remove_timeout(timeout_handle)
        assert future_cell[0] is not None
        if future_cell[0].cancelled() or not future_cell[0].done():
            raise TimeoutError("Operation timed out after %s seconds" % timeout)
        return future_cell[0].result()

    def time(self) -> float:
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        Historically, the IOLoop could be customized to use e.g.
        `time.monotonic` instead of `time.time`, but this is not
        currently supported and so this method is equivalent to
        `time.time`.

        """
        return time.time()

    def add_timeout(
        self,
        deadline: Union[float, datetime.timedelta],
        callback: Callable,
        *args: Any,
        **kwargs: Any
    ) -> object:
        """Runs the ``callback`` at the time ``deadline`` from the I/O loop.

        Returns an opaque handle that may be passed to
        `remove_timeout` to cancel.

        ``deadline`` may be a number denoting a time (on the same
        scale as `IOLoop.time`, normally `time.time`), or a
        `datetime.timedelta` object for a deadline relative to the
        current time.  Since Tornado 4.0, `call_later` is a more
        convenient alternative for the relative case since it does not
        require a timedelta object.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        `IOLoop`'s thread, and then call `add_timeout` from there.

        Subclasses of IOLoop must implement either `add_timeout` or
        `call_at`; the default implementations of each will call
        the other.  `call_at` is usually easier to implement, but
        subclasses that wish to maintain compatibility with Tornado
        versions prior to 4.0 must use `add_timeout` instead.

        .. versionchanged:: 4.0
           Now passes through ``*args`` and ``**kwargs`` to the callback.
        """
        if isinstance(deadline, numbers.Real):
            return self.call_at(deadline, callback, *args, **kwargs)
        elif isinstance(deadline, datetime.timedelta):
            return self.call_at(
                self.time() + deadline.total_seconds(), callback, *args, **kwargs
            )
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(
        self, delay: float, callback: Callable, *args: Any, **kwargs: Any
    ) -> object:
        """Runs the ``callback`` after ``delay`` seconds have passed.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.call_at(self.time() + delay, callback, *args, **kwargs)

    def call_at(
        self, when: float, callback: Callable, *args: Any, **kwargs: Any
    ) -> object:
        """Runs the ``callback`` at the absolute time designated by ``when``.

        ``when`` must be a number using the same reference point as
        `IOLoop.time`.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.add_timeout(when, callback, *args, **kwargs)

    def remove_timeout(self, timeout: object) -> None:
        """Cancels a pending timeout.

        The argument is a handle as returned by `add_timeout`.  It is
        safe to call `remove_timeout` even if the callback has already
        been run.
        """
        raise NotImplementedError()

    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
        """Calls the given callback on the next I/O loop iteration.

        It is safe to call this method from any thread at any time,
        except from a signal handler.  Note that this is the **only**
        method in `IOLoop` that makes this thread-safety guarantee; all
        other interaction with the `IOLoop` must be done from that
        `IOLoop`'s thread.  `add_callback()` may be used to transfer
        control from other threads to the `IOLoop`'s thread.
        """
        raise NotImplementedError()

    def add_callback_from_signal(
        self, callback: Callable, *args: Any, **kwargs: Any
    ) -> None:
        """Calls the given callback on the next I/O loop iteration.

        Intended to be afe for use from a Python signal handler; should not be
        used otherwise.

        .. deprecated:: 6.4
           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.
           This method is suspected to have been broken since Tornado 5.0 and
           will be removed in version 7.0.
        """
        raise NotImplementedError()

    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
        """Calls the given callback on the next IOLoop iteration.

        As of Tornado 6.0, this method is equivalent to `add_callback`.

        .. versionadded:: 4.0
        """
        self.add_callback(callback, *args, **kwargs)

    def add_future(
        self,
        future: "Union[Future[_T], concurrent.futures.Future[_T]]",
        callback: Callable[["Future[_T]"], None],
    ) -> None:
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.

        This method only accepts `.Future` objects and not other
        awaitables (unlike most of Tornado where the two are
        interchangeable).
        """
        if isinstance(future, Future):
            # Note that we specifically do not want the inline behavior of
            # tornado.concurrent.future_add_done_callback. We always want
            # this callback scheduled on the next IOLoop iteration (which
            # asyncio.Future always does).
            #
            # Wrap the callback in self._run_callback so we control
            # the error logging (i.e. it goes to tornado.log.app_log
            # instead of asyncio's log).
            future.add_done_callback(
                lambda f: self._run_callback(functools.partial(callback, future))
            )
        else:
            assert is_future(future)
            # For concurrent futures, we use self.add_callback, so
            # it's fine if future_add_done_callback inlines that call.
            future_add_done_callback(
                future, lambda f: self.add_callback(callback, future)
            )

    def run_in_executor(
        self,
        executor: Optional[concurrent.futures.Executor],
        func: Callable[..., _T],
        *args: Any
    ) -> "Future[_T]":
        """Runs a function in a ``concurrent.futures.Executor``. If
        ``executor`` is ``None``, the IO loop's default executor will be used.

        Use `functools.partial` to pass keyword arguments to ``func``.

        .. versionadded:: 5.0
        """
        if executor is None:
            if not hasattr(self, "_executor"):
                from tornado.process import cpu_count

                self._executor = concurrent.futures.ThreadPoolExecutor(
                    max_workers=(cpu_count() * 5)
                )  # type: concurrent.futures.Executor
            executor = self._executor
        c_future = executor.submit(func, *args)
        # Concurrent Futures are not usable with await. Wrap this in a
        # Tornado Future instead, using self.add_future for thread-safety.
        t_future = Future()  # type: Future[_T]
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
        """Sets the default executor to use with :meth:`run_in_executor`.

        .. versionadded:: 5.0
        """
        self._executor = executor

    def _run_callback(self, callback: Callable[[], Any]) -> None:
        """Runs a callback with error handling.

        .. versionchanged:: 6.0

           CancelledErrors are no longer logged.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen

                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, self._discard_future_result)
        except asyncio.CancelledError:
            pass
        except Exception:
            app_log.error("Exception in callback %r", callback, exc_info=True)

    def _discard_future_result(self, future: Future) -> None:
        """Avoid unhandled-exception warnings from spawned coroutines."""
        future.result()

    def split_fd(
        self, fd: Union[int, _Selectable]
    ) -> Tuple[int, Union[int, _Selectable]]:
        # """Returns an (fd, obj) pair from an ``fd`` parameter.

        # We accept both raw file descriptors and file-like objects as
        # input to `add_handler` and related methods.  When a file-like
        # object is passed, we must retain the object itself so we can
        # close it correctly when the `IOLoop` shuts down, but the
        # poller interfaces favor file descriptors (they will accept
        # file-like objects and call ``fileno()`` for you, but they
        # always return the descriptor itself).

        # This method is provided for use by `IOLoop` subclasses and should
        # not generally be used by application code.

        # .. versionadded:: 4.0
        # """
        if isinstance(fd, int):
            return fd, fd
        return fd.fileno(), fd

    def close_fd(self, fd: Union[int, _Selectable]) -> None:
        # """Utility method to close an ``fd``.

        # If ``fd`` is a file-like object, we close it directly; otherwise
        # we use `os.close`.

        # This method is provided for use by `IOLoop` subclasses (in
        # implementations of ``IOLoop.close(all_fds=True)`` and should
        # not generally be used by application code.

        # .. versionadded:: 4.0
        # """
        try:
            if isinstance(fd, int):
                os.close(fd)
            else:
                fd.close()
        except OSError:
            pass

    def _register_task(self, f: Future) -> None:
        self._pending_tasks.add(f)

    def _unregister_task(self, f: Future) -> None:
        self._pending_tasks.discard(f)


class _Timeout(object):
    """An IOLoop timeout, a UNIX timestamp and a callback"""

    # Reduce memory overhead when there are lots of pending callbacks
    __slots__ = ["deadline", "callback", "tdeadline"]

    def __init__(
        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (
            deadline,
            next(io_loop._timeout_counter),
        )  # type: Tuple[float, int]

    # Comparison methods to sort by deadline, with object id as a tiebreaker
    # to guarantee a consistent ordering.  The heapq module uses __le__
    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
    # use __lt__).
    def __lt__(self, other: "_Timeout") -> bool:
        return self.tdeadline < other.tdeadline

    def __le__(self, other: "_Timeout") -> bool:
        return self.tdeadline <= other.tdeadline


class PeriodicCallback(object):
    """Schedules the given callback to be called periodically.

    The callback is called every ``callback_time`` milliseconds when
    ``callback_time`` is a float. Note that the timeout is given in
    milliseconds, while most other time-related functions in Tornado use
    seconds. ``callback_time`` may alternatively be given as a
    `datetime.timedelta` object.

    If ``jitter`` is specified, each callback time will be randomly selected
    within a window of ``jitter * callback_time`` milliseconds.
    Jitter can be used to reduce alignment of events with similar periods.
    A jitter of 0.1 means allowing a 10% variation in callback time.
    The window is centered on ``callback_time`` so the total number of calls
    within a given interval should not be significantly affected by adding
    jitter.

    If the callback runs for longer than ``callback_time`` milliseconds,
    subsequent invocations will be skipped to get back on schedule.

    `start` must be called after the `PeriodicCallback` is created.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.1
       The ``jitter`` argument is added.

    .. versionchanged:: 6.2
       If the ``callback`` argument is a coroutine, and a callback runs for
       longer than ``callback_time``, subsequent invocations will be skipped.
       Previously this was only true for regular functions, not coroutines,
       which were "fire-and-forget" for `PeriodicCallback`.

       The ``callback_time`` argument now accepts `datetime.timedelta` objects,
       in addition to the previous numeric milliseconds.
    """

    def __init__(
        self,
        callback: Callable[[], Optional[Awaitable]],
        callback_time: Union[datetime.timedelta, float],
        jitter: float = 0,
    ) -> None:
        self.callback = callback
        if isinstance(callback_time, datetime.timedelta):
            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)
        else:
            if callback_time <= 0:
                raise ValueError("Periodic callback must have a positive callback_time")
            self.callback_time = callback_time
        self.jitter = jitter
        self._running = False
        self._timeout = None  # type: object

    def start(self) -> None:
        """Starts the timer."""
        # Looking up the IOLoop here allows to first instantiate the
        # PeriodicCallback in another thread, then start it using
        # IOLoop.add_callback().
        self.io_loop = IOLoop.current()
        self._running = True
        self._next_timeout = self.io_loop.time()
        self._schedule_next()

    def stop(self) -> None:
        """Stops the timer."""
        self._running = False
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def is_running(self) -> bool:
        """Returns ``True`` if this `.PeriodicCallback` has been started.

        .. versionadded:: 4.1
        """
        return self._running

    async def _run(self) -> None:
        if not self._running:
            return
        try:
            val = self.callback()
            if val is not None and isawaitable(val):
                await val
        except Exception:
            app_log.error("Exception in callback %r", self.callback, exc_info=True)
        finally:
            self._schedule_next()

    def _schedule_next(self) -> None:
        if self._running:
            self._update_next(self.io_loop.time())
            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)

    def _update_next(self, current_time: float) -> None:
        callback_time_sec = self.callback_time / 1000.0
        if self.jitter:
            # apply jitter fraction
            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
        if self._next_timeout <= current_time:
            # The period should be measured from the start of one call
            # to the start of the next. If one call takes too long,
            # skip cycles to get back to a multiple of the original
            # schedule.
            self._next_timeout += (
                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1
            ) * callback_time_sec
        else:
            # If the clock moved backwards, ensure we advance the next
            # timeout instead of recomputing the same value again.
            # This may result in long gaps between callbacks if the
            # clock jumps backwards by a lot, but the far more common
            # scenario is a small NTP adjustment that should just be
            # ignored.
            #
            # Note that on some systems if time.time() runs slower
            # than time.monotonic() (most common on windows), we
            # effectively experience a small backwards time jump on
            # every iteration because PeriodicCallback uses
            # time.time() while asyncio schedules callbacks using
            # time.monotonic().
            # https://github.com/tornadoweb/tornado/issues/2333
            self._next_timeout += callback_time_sec

```
--- 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:** Reference Cycles Created by Callback Closures in IOLoop.add_future

**Description:**
When adding a callback to a future using a lambda that captures the future instance, a reference cycle is created. This cycle prevents the garbage collector from reclaiming the memory promptly, potentially leading to memory leaks and slower garbage collection.

**Example Code:**
```python
from tornado.ioloop import IOLoop
from tornado.concurrent import Future

def callback(fut):
    pass

loop = IOLoop.current()
future = Future()
future.add_done_callback(lambda f: callback(future))
loop.run_sync(lambda: future.set_result(None))
```

**Expected Behavior:**
After the future is completed and the callback is executed, there should be no reference cycles involving the future and the callback. The garbage collector should be able to reclaim the memory without delays.

**Actual Behavior:**
Using a lambda that captures the `future` creates a reference cycle between the future and the callback. This prevents the garbage collector from promptly reclaiming the memory, leading to potential memory leaks and degraded performance over time.

[/ISSUE]
{
    "CircleRefsTest.test_async_handler": "PASSED",
    "CircleRefsTest.test_coro_handler": "PASSED",
    "CircleRefsTest.test_finish_exception_handler": "PASSED",
    "CircleRefsTest.test_known_leak": "FAILED",
    "CircleRefsTest.test_run_on_executor": "PASSED",
    "CircleRefsTest.test_sync_handler": "PASSED"
}
diff --git a/tornado/concurrent.py b/tornado/concurrent.py
index 6e05346b..f0bbf623 100644
--- a/tornado/concurrent.py
+++ b/tornado/concurrent.py
@@ -150,8 +150,7 @@ def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
 
     """
 
-    def copy(future: "Future[_T]") -> None:
-        assert future is a
+    def copy(a: "Future[_T]") -> None:
         if b.done():
             return
         if hasattr(a, "exc_info") and a.exc_info() is not None:  # type: ignore
diff --git a/tornado/ioloop.py b/tornado/ioloop.py
index cdfb4a63..3fb1359a 100644
--- a/tornado/ioloop.py
+++ b/tornado/ioloop.py
@@ -696,15 +696,13 @@ class IOLoop(Configurable):
             # the error logging (i.e. it goes to tornado.log.app_log
             # instead of asyncio's log).
             future.add_done_callback(
-                lambda f: self._run_callback(functools.partial(callback, future))
+                lambda f: self._run_callback(functools.partial(callback, f))
             )
         else:
             assert is_future(future)
             # For concurrent futures, we use self.add_callback, so
             # it's fine if future_add_done_callback inlines that call.
-            future_add_done_callback(
-                future, lambda f: self.add_callback(callback, future)
-            )
+            future_add_done_callback(future, lambda f: self.add_callback(callback, f))
 
     def run_in_executor(
         self,

{"tornado/concurrent.py": "#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Utilities for working with ``Future`` objects.\n\nTornado previously provided its own ``Future`` class, but now uses\n`asyncio.Future`. This module contains utility functions for working\nwith `asyncio.Future` in a way that is backwards-compatible with\nTornado's old ``Future`` implementation.\n\nWhile this module is an important part of Tornado's internal\nimplementation, applications rarely need to interact with it\ndirectly.\n\n\"\"\"\n\nimport asyncio\nfrom concurrent import futures\nimport functools\nimport sys\nimport types\n\nfrom tornado.log import app_log\n\nimport typing\nfrom typing import Any, Callable, Optional, Tuple, Union\n\n_T = typing.TypeVar(\"_T\")\n\n\nclass ReturnValueIgnoredError(Exception):\n    # No longer used; was previously used by @return_future\n    pass\n\n\nFuture = asyncio.Future\n\nFUTURES = (futures.Future, Future)\n\n\ndef is_future(x: Any) -> bool:\n    return isinstance(x, FUTURES)\n\n\nclass DummyExecutor(futures.Executor):\n    def submit(\n        self, fn: Callable[..., _T], *args: Any, **kwargs: Any\n    ) -> \"futures.Future[_T]\":\n        future = futures.Future()  # type: futures.Future[_T]\n        try:\n            future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n        except Exception:\n            future_set_exc_info(future, sys.exc_info())\n        return future\n\n    def shutdown(self, wait: bool = True) -> None:\n        pass\n\n\ndummy_executor = DummyExecutor()\n\n\ndef run_on_executor(*args: Any, **kwargs: Any) -> Callable:\n    \"\"\"Decorator to run a synchronous method asynchronously on an executor.\n\n    Returns a future.\n\n    The executor to be used is determined by the ``executor``\n    attributes of ``self``. To use a different attribute name, pass a\n    keyword argument to the decorator::\n\n        @run_on_executor(executor='_thread_pool')\n        def foo(self):\n            pass\n\n    This decorator should not be confused with the similarly-named\n    `.IOLoop.run_in_executor`. In general, using ``run_in_executor``\n    when *calling* a blocking method is recommended instead of using\n    this decorator when *defining* a method. If compatibility with older\n    versions of Tornado is required, consider defining an executor\n    and using ``executor.submit()`` at the call site.\n\n    .. versionchanged:: 4.2\n       Added keyword arguments to use alternative attributes.\n\n    .. versionchanged:: 5.0\n       Always uses the current IOLoop instead of ``self.io_loop``.\n\n    .. versionchanged:: 5.1\n       Returns a `.Future` compatible with ``await`` instead of a\n       `concurrent.futures.Future`.\n\n    .. deprecated:: 5.1\n\n       The ``callback`` argument is deprecated and will be removed in\n       6.0. The decorator itself is discouraged in new code but will\n       not be removed in 6.0.\n\n    .. versionchanged:: 6.0\n\n       The ``callback`` argument was removed.\n    \"\"\"\n    # Fully type-checking decorators is tricky, and this one is\n    # discouraged anyway so it doesn't have all the generic magic.\n    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:\n        executor = kwargs.get(\"executor\", \"executor\")\n\n        @functools.wraps(fn)\n        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:\n            async_future = Future()  # type: Future\n            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)\n            chain_future(conc_future, async_future)\n            return async_future\n\n        return wrapper\n\n    if args and kwargs:\n        raise ValueError(\"cannot combine positional and keyword args\")\n    if len(args) == 1:\n        return run_on_executor_decorator(args[0])\n    elif len(args) != 0:\n        raise ValueError(\"expected 1 argument, got %d\", len(args))\n    return run_on_executor_decorator\n\n\n_NO_RESULT = object()\n\n\ndef chain_future(a: \"Future[_T]\", b: \"Future[_T]\") -> None:\n    \"\"\"Chain two futures together so that when one completes, so does the other.\n\n    The result (success or failure) of ``a`` will be copied to ``b``, unless\n    ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n    .. versionchanged:: 5.0\n\n       Now accepts both Tornado/asyncio `Future` objects and\n       `concurrent.futures.Future`.\n\n    \"\"\"\n\n    def copy(future: \"Future[_T]\") -> None:\n        assert future is a\n        if b.done():\n            return\n        if hasattr(a, \"exc_info\") and a.exc_info() is not None:  # type: ignore\n            future_set_exc_info(b, a.exc_info())  # type: ignore\n        else:\n            a_exc = a.exception()\n            if a_exc is not None:\n                b.set_exception(a_exc)\n            else:\n                b.set_result(a.result())\n\n    if isinstance(a, Future):\n        future_add_done_callback(a, copy)\n    else:\n        # concurrent.futures.Future\n        from tornado.ioloop import IOLoop\n\n        IOLoop.current().add_future(a, copy)\n\n\ndef future_set_result_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", value: _T\n) -> None:\n    \"\"\"Set the given ``value`` as the `Future`'s result, if not cancelled.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if not future.cancelled():\n        future.set_result(value)\n\n\ndef future_set_exception_unless_cancelled(\n    future: \"Union[futures.Future[_T], Future[_T]]\", exc: BaseException\n) -> None:\n    \"\"\"Set the given ``exc`` as the `Future`'s exception.\n\n    If the Future is already canceled, logs the exception instead. If\n    this logging is not desired, the caller should explicitly check\n    the state of the Future and call ``Future.set_exception`` instead of\n    this wrapper.\n\n    Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on\n    a cancelled `asyncio.Future`.\n\n    .. versionadded:: 6.0\n\n    \"\"\"\n    if not future.cancelled():\n        future.set_exception(exc)\n    else:\n        app_log.error(\"Exception after Future was cancelled\", exc_info=exc)\n\n\ndef future_set_exc_info(\n    future: \"Union[futures.Future[_T], Future[_T]]\",\n    exc_info: Tuple[\n        Optional[type], Optional[BaseException], Optional[types.TracebackType]\n    ],\n) -> None:\n    \"\"\"Set the given ``exc_info`` as the `Future`'s exception.\n\n    Understands both `asyncio.Future` and the extensions in older\n    versions of Tornado to enable better tracebacks on Python 2.\n\n    .. versionadded:: 5.0\n\n    .. versionchanged:: 6.0\n\n       If the future is already cancelled, this function is a no-op.\n       (previously ``asyncio.InvalidStateError`` would be raised)\n\n    \"\"\"\n    if exc_info[1] is None:\n        raise Exception(\"future_set_exc_info called with no exception\")\n    future_set_exception_unless_cancelled(future, exc_info[1])\n\n\n@typing.overload\ndef future_add_done_callback(\n    future: \"futures.Future[_T]\", callback: Callable[[\"futures.Future[_T]\"], None]\n) -> None:\n    pass\n\n\n@typing.overload  # noqa: F811\ndef future_add_done_callback(\n    future: \"Future[_T]\", callback: Callable[[\"Future[_T]\"], None]\n) -> None:\n    pass\n\n\ndef future_add_done_callback(  # noqa: F811\n    future: \"Union[futures.Future[_T], Future[_T]]\", callback: Callable[..., None]\n) -> None:\n    \"\"\"Arrange to call ``callback`` when ``future`` is complete.\n\n    ``callback`` is invoked with one argument, the ``future``.\n\n    If ``future`` is already done, ``callback`` is invoked immediately.\n    This may differ from the behavior of ``Future.add_done_callback``,\n    which makes no such guarantee.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    if future.done():\n        callback(future)\n    else:\n        future.add_done_callback(callback)\n", "tornado/ioloop.py": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a\nslightly different interface. The `.IOLoop` interface is now provided primarily\nfor backwards compatibility; new code should generally use the `asyncio` event\nloop interface directly. The `IOLoop.current` class method provides the\n`IOLoop` instance corresponding to the running `asyncio` event loop.\n\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\nimport warnings\nfrom inspect import isawaitable\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List, Set  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import asyncio\n        import errno\n        import functools\n        import socket\n\n        import tornado\n        from tornado.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(handle_connection, connection, address)\n\n        async def main():\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            await asyncio.Event().wait()\n\n        if __name__ == \"__main__\":\n            asyncio.run(main())\n\n    .. testoutput::\n       :hide:\n\n    Most applications should not attempt to construct an `IOLoop` directly,\n    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.\n    In some cases, such as in test frameworks when initializing an `IOLoop`\n    to be run in a secondary thread, it may be appropriate to construct\n    an `IOLoop` with ``IOLoop(make_current=False)``.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across processes\n    in any way. When multiple processes are being used, each process should\n    create its own `IOLoop`, which also implies that any objects which depend on\n    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child\n    processes. As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as early as\n    possible, ideally the first thing the application does after loading its\n    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method\n       cannot be used on Python 3 except to redundantly specify the `asyncio`\n       event loop.\n\n    .. versionchanged:: 6.3\n       ``make_current=True`` is now the default when creating an IOLoop -\n       previously the default was to make the event loop current if there wasn't\n       already a current one.\n    \"\"\"\n\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    # Maintain a set of all pending tasks to follow the warning in the docs\n    # of asyncio.create_tasks:\n    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task\n    # This ensures that all pending tasks have a strong reference so they\n    # will not be garbage collected before they are finished.\n    # (Thus avoiding \"task was destroyed but it is pending\" warnings)\n    # An analogous change has been proposed in cpython for 3.13:\n    # https://github.com/python/cpython/issues/91887\n    # If that change is accepted, this can eventually be removed.\n    # If it is not, we will consider the rationale and may remove this.\n    _pending_tasks = set()  # type: Set[Future]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        from tornado.platform.asyncio import BaseAsyncIOLoop\n\n        if isinstance(impl, str):\n            impl = import_object(impl)\n        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n            raise RuntimeError(\"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self) -> None:\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance() -> None:\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n\n        .. deprecated:: 6.2\n           It is deprecated to call ``IOLoop.current()`` when no `asyncio`\n           event loop is running.\n        \"\"\"\n        try:\n            loop = asyncio.get_event_loop()\n        except RuntimeError:\n            if not instance:\n                return None\n            # Create a new asyncio event loop for this thread.\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n\n        try:\n            return IOLoop._ioloop_for_asyncio[loop]\n        except KeyError:\n            if instance:\n                from tornado.platform.asyncio import AsyncIOMainLoop\n\n                current = AsyncIOMainLoop()  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n\n        .. deprecated:: 6.2\n           Setting and clearing the current event loop through Tornado is\n           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.\n        \"\"\"\n        warnings.warn(\n            \"make_current is deprecated; start the event loop first\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        self._make_current()\n\n    def _make_current(self) -> None:\n        # The asyncio event loops override this method.\n        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        .. deprecated:: 6.2\n        \"\"\"\n        warnings.warn(\n            \"clear_current is deprecated\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        IOLoop._clear_current()\n\n    @staticmethod\n    def _clear_current() -> None:\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n\n    def _clear_current_hook(self) -> None:\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: bool = True) -> None:\n        if make_current:\n            self._make_current()\n\n    def close(self, all_fds: bool = False) -> None:\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` and ``close()`` method.\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd: Union[int, _Selectable]) -> None:\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def start(self) -> None:\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def stop(self) -> None:\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `asyncio.TimeoutError` is raised.\n\n        This method is useful to allow asynchronous calls in a\n        ``main()`` function::\n\n            async def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        .. versionchanged:: 6.2\n           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        assert future_cell[0] is not None\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError(\"Operation timed out after %s seconds\" % timeout)\n        return future_cell[0].result()\n\n    def time(self) -> float:\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable,\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(\n        self, when: float, callback: Callable, *args: Any, **kwargs: Any\n    ) -> object:\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout: object) -> None:\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Intended to be afe for use from a Python signal handler; should not be\n        used otherwise.\n\n        .. deprecated:: 6.4\n           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.\n           This method is suspected to have been broken since Tornado 5.0 and\n           will be removed in version 7.0.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n\n        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> \"Future[_T]\":\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()  # type: Future[_T]\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\n        # \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        # We accept both raw file descriptors and file-like objects as\n        # input to `add_handler` and related methods.  When a file-like\n        # object is passed, we must retain the object itself so we can\n        # close it correctly when the `IOLoop` shuts down, but the\n        # poller interfaces favor file descriptors (they will accept\n        # file-like objects and call ``fileno()`` for you, but they\n        # always return the descriptor itself).\n\n        # This method is provided for use by `IOLoop` subclasses and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\n        # \"\"\"Utility method to close an ``fd``.\n\n        # If ``fd`` is a file-like object, we close it directly; otherwise\n        # we use `os.close`.\n\n        # This method is provided for use by `IOLoop` subclasses (in\n        # implementations of ``IOLoop.close(all_fds=True)`` and should\n        # not generally be used by application code.\n\n        # .. versionadded:: 4.0\n        # \"\"\"\n        try:\n            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\n\n    def _register_task(self, f: Future) -> None:\n        self._pending_tasks.add(f)\n\n    def _unregister_task(self, f: Future) -> None:\n        self._pending_tasks.discard(f)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = [\"deadline\", \"callback\", \"tdeadline\"]\n\n    def __init__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds when\n    ``callback_time`` is a float. Note that the timeout is given in\n    milliseconds, while most other time-related functions in Tornado use\n    seconds. ``callback_time`` may alternatively be given as a\n    `datetime.timedelta` object.\n\n    If ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n\n    .. versionchanged:: 6.2\n       If the ``callback`` argument is a coroutine, and a callback runs for\n       longer than ``callback_time``, subsequent invocations will be skipped.\n       Previously this was only true for regular functions, not coroutines,\n       which were \"fire-and-forget\" for `PeriodicCallback`.\n\n       The ``callback_time`` argument now accepts `datetime.timedelta` objects,\n       in addition to the previous numeric milliseconds.\n    \"\"\"\n\n    def __init__(\n        self,\n        callback: Callable[[], Optional[Awaitable]],\n        callback_time: Union[datetime.timedelta, float],\n        jitter: float = 0,\n    ) -> None:\n        self.callback = callback\n        if isinstance(callback_time, datetime.timedelta):\n            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)\n        else:\n            if callback_time <= 0:\n                raise ValueError(\"Periodic callback must have a positive callback_time\")\n            self.callback_time = callback_time\n        self.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self) -> None:\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    async def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            val = self.callback()\n            if val is not None and isawaitable(val):\n                await val\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\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:** Reference Cycles Created by Callback Closures in IOLoop.add_future

**Description:**
When adding a callback to a future using a lambda that captures the future instance, a reference cycle is created. This cycle prevents the garbage collector from reclaiming the memory promptly, potentially leading to memory leaks and slower garbage collection.

**Example Code:**
```python
from tornado.ioloop import IOLoop
from tornado.concurrent import Future

def callback(fut):
    pass

loop = IOLoop.current()
future = Future()
future.add_done_callback(lambda f: callback(future))
loop.run_sync(lambda: future.set_result(None))
```

**Expected Behavior:**
After the future is completed and the callback is executed, there should be no reference cycles involving the future and the callback. The garbage collector should be able to reclaim the memory without delays.

**Actual Behavior:**
Using a lambda that captures the `future` creates a reference cycle between the future and the callback. This prevents the garbage collector from promptly reclaiming the memory, leading to potential memory leaks and degraded performance over time.

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

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

--- BEGIN FILE ---
```
### tornado/concurrent.py
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for working with ``Future`` objects.

Tornado previously provided its own ``Future`` class, but now uses
`asyncio.Future`. This module contains utility functions for working
with `asyncio.Future` in a way that is backwards-compatible with
Tornado's old ``Future`` implementation.

While this module is an important part of Tornado's internal
implementation, applications rarely need to interact with it
directly.

"""

import asyncio
from concurrent import futures
import functools
import sys
import types

from tornado.log import app_log

import typing
from typing import Any, Callable, Optional, Tuple, Union

_T = typing.TypeVar("_T")


class ReturnValueIgnoredError(Exception):
    # No longer used; was previously used by @return_future
    pass


Future = asyncio.Future

FUTURES = (futures.Future, Future)


def is_future(x: Any) -> bool:
    return isinstance(x, FUTURES)


class DummyExecutor(futures.Executor):
    def submit(
        self, fn: Callable[..., _T], *args: Any, **kwargs: Any
    ) -> "futures.Future[_T]":
        future = futures.Future()  # type: futures.Future[_T]
        try:
            future_set_result_unless_cancelled(future, fn(*args, **kwargs))
        except Exception:
            future_set_exc_info(future, sys.exc_info())
        return future

    def shutdown(self, wait: bool = True) -> None:
        pass


dummy_executor = DummyExecutor()


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

    Returns a future.

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

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

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

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

    .. versionchanged:: 5.0
       Always uses the current IOLoop instead of ``self.io_loop``.

    .. versionchanged:: 5.1
       Returns a `.Future` compatible with ``await`` instead of a
       `concurrent.futures.Future`.

    .. deprecated:: 5.1

       The ``callback`` argument is deprecated and will be removed in
       6.0. The decorator itself is discouraged in new code but will
       not be removed in 6.0.

    .. versionchanged:: 6.0

       The ``callback`` argument was removed.
    """
    # Fully type-checking decorators is tricky, and this one is
    # discouraged anyway so it doesn't have all the generic magic.
    def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]:
        executor = kwargs.get("executor", "executor")

        @functools.wraps(fn)
        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future:
            async_future = Future()  # type: Future
            conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs)
            chain_future(conc_future, async_future)
            return async_future

        return wrapper

    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator


_NO_RESULT = object()


def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
    """Chain two futures together so that when one completes, so does the other.

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

    .. versionchanged:: 5.0

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

    """

    def copy(future: "Future[_T]") -> None:
        assert future is a
        if b.done():
            return
        if hasattr(a, "exc_info") and a.exc_info() is not None:  # type: ignore
            future_set_exc_info(b, a.exc_info())  # type: ignore
        else:
            a_exc = a.exception()
            if a_exc is not None:
                b.set_exception(a_exc)
            else:
                b.set_result(a.result())

    if isinstance(a, Future):
        future_add_done_callback(a, copy)
    else:
        # concurrent.futures.Future
        from tornado.ioloop import IOLoop

        IOLoop.current().add_future(a, copy)


def future_set_result_unless_cancelled(
    future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
    """Set the given ``value`` as the `Future`'s result, if not cancelled.

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

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


def future_set_exception_unless_cancelled(
    future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
    """Set the given ``exc`` as the `Future`'s exception.

    If the Future is already canceled, logs the exception instead. If
    this logging is not desired, the caller should explicitly check
    the state of the Future and call ``Future.set_exception`` instead of
    this wrapper.

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

    .. versionadded:: 6.0

    """
    if not future.cancelled():
        future.set_exception(exc)
    else:
        app_log.error("Exception after Future was cancelled", exc_info=exc)


def future_set_exc_info(
    future: "Union[futures.Future[_T], Future[_T]]",
    exc_info: Tuple[
        Optional[type], Optional[BaseException], Optional[types.TracebackType]
    ],
) -> None:
    """Set the given ``exc_info`` as the `Future`'s exception.

    Understands both `asyncio.Future` and the extensions in older
    versions of Tornado to enable better tracebacks on Python 2.

    .. versionadded:: 5.0

    .. versionchanged:: 6.0

       If the future is already cancelled, this function is a no-op.
       (previously ``asyncio.InvalidStateError`` would be raised)

    """
    if exc_info[1] is None:
        raise Exception("future_set_exc_info called with no exception")
    future_set_exception_unless_cancelled(future, exc_info[1])


@typing.overload
def future_add_done_callback(
    future: "futures.Future[_T]", callback: Callable[["futures.Future[_T]"], None]
) -> None:
    pass


@typing.overload  # noqa: F811
def future_add_done_callback(
    future: "Future[_T]", callback: Callable[["Future[_T]"], None]
) -> None:
    pass


def future_add_done_callback(  # noqa: F811
    future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None]
) -> None:
    """Arrange to call ``callback`` when ``future`` is complete.

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

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

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


### tornado/ioloop.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""An I/O event loop for non-blocking sockets.

In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a
slightly different interface. The `.IOLoop` interface is now provided primarily
for backwards compatibility; new code should generally use the `asyncio` event
loop interface directly. The `IOLoop.current` class method provides the
`IOLoop` instance corresponding to the running `asyncio` event loop.

"""

import asyncio
import concurrent.futures
import datetime
import functools
import numbers
import os
import sys
import time
import math
import random
import warnings
from inspect import isawaitable

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
)
from tornado.log import app_log
from tornado.util import Configurable, TimeoutError, import_object

import typing
from typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable

if typing.TYPE_CHECKING:
    from typing import Dict, List, Set  # noqa: F401

    from typing_extensions import Protocol
else:
    Protocol = object


class _Selectable(Protocol):
    def fileno(self) -> int:
        pass

    def close(self) -> None:
        pass


_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)


class IOLoop(Configurable):
    """An I/O event loop.

    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop.

    Example usage for a simple TCP server:

    .. testcode::

        import asyncio
        import errno
        import functools
        import socket

        import tornado
        from tornado.iostream import IOStream

        async def handle_connection(connection, address):
            stream = IOStream(connection)
            message = await stream.read_until_close()
            print("message from client:", message.decode().strip())

        def connection_ready(sock, fd, events):
            while True:
                try:
                    connection, address = sock.accept()
                except BlockingIOError:
                    return
                connection.setblocking(0)
                io_loop = tornado.ioloop.IOLoop.current()
                io_loop.spawn_callback(handle_connection, connection, address)

        async def main():
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setblocking(0)
            sock.bind(("", 8888))
            sock.listen(128)

            io_loop = tornado.ioloop.IOLoop.current()
            callback = functools.partial(connection_ready, sock)
            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
            await asyncio.Event().wait()

        if __name__ == "__main__":
            asyncio.run(main())

    .. testoutput::
       :hide:

    Most applications should not attempt to construct an `IOLoop` directly,
    and instead initialize the `asyncio` event loop and use `IOLoop.current()`.
    In some cases, such as in test frameworks when initializing an `IOLoop`
    to be run in a secondary thread, it may be appropriate to construct
    an `IOLoop` with ``IOLoop(make_current=False)``.

    In general, an `IOLoop` cannot survive a fork or be shared across processes
    in any way. When multiple processes are being used, each process should
    create its own `IOLoop`, which also implies that any objects which depend on
    the `IOLoop` (such as `.AsyncHTTPClient`) must also be created in the child
    processes. As a guideline, anything that starts processes (including the
    `tornado.process` and `multiprocessing` modules) should do so as early as
    possible, ideally the first thing the application does after loading its
    configuration, and *before* any calls to `.IOLoop.start` or `asyncio.run`.

    .. versionchanged:: 4.2
       Added the ``make_current`` keyword argument to the `IOLoop`
       constructor.

    .. versionchanged:: 5.0

       Uses the `asyncio` event loop by default. The ``IOLoop.configure`` method
       cannot be used on Python 3 except to redundantly specify the `asyncio`
       event loop.

    .. versionchanged:: 6.3
       ``make_current=True`` is now the default when creating an IOLoop -
       previously the default was to make the event loop current if there wasn't
       already a current one.
    """

    # These constants were originally based on constants from the epoll module.
    NONE = 0
    READ = 0x001
    WRITE = 0x004
    ERROR = 0x018

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]

    # Maintain a set of all pending tasks to follow the warning in the docs
    # of asyncio.create_tasks:
    # https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task
    # This ensures that all pending tasks have a strong reference so they
    # will not be garbage collected before they are finished.
    # (Thus avoiding "task was destroyed but it is pending" warnings)
    # An analogous change has been proposed in cpython for 3.13:
    # https://github.com/python/cpython/issues/91887
    # If that change is accepted, this can eventually be removed.
    # If it is not, we will consider the rationale and may remove this.
    _pending_tasks = set()  # type: Set[Future]

    @classmethod
    def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        from tornado.platform.asyncio import BaseAsyncIOLoop

        if isinstance(impl, str):
            impl = import_object(impl)
        if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
            raise RuntimeError("only AsyncIOLoop is allowed when asyncio is available")
        super(IOLoop, cls).configure(impl, **kwargs)

    @staticmethod
    def instance() -> "IOLoop":
        """Deprecated alias for `IOLoop.current()`.

        .. versionchanged:: 5.0

           Previously, this method returned a global singleton
           `IOLoop`, in contrast with the per-thread `IOLoop` returned
           by `current()`. In nearly all cases the two were the same
           (when they differed, it was generally used from non-Tornado
           threads to communicate back to the main thread's `IOLoop`).
           This distinction is not present in `asyncio`, so in order
           to facilitate integration with that package `instance()`
           was changed to be an alias to `current()`. Applications
           using the cross-thread communications aspect of
           `instance()` should instead set their own global variable
           to point to the `IOLoop` they want to use.

        .. deprecated:: 5.0
        """
        return IOLoop.current()

    def install(self) -> None:
        """Deprecated alias for `make_current()`.

        .. versionchanged:: 5.0

           Previously, this method would set this `IOLoop` as the
           global singleton used by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`, `install()`
           is an alias for `make_current()`.

        .. deprecated:: 5.0
        """
        self.make_current()

    @staticmethod
    def clear_instance() -> None:
        """Deprecated alias for `clear_current()`.

        .. versionchanged:: 5.0

           Previously, this method would clear the `IOLoop` used as
           the global singleton by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`,
           `clear_instance()` is an alias for `clear_current()`.

        .. deprecated:: 5.0

        """
        IOLoop.clear_current()

    @typing.overload
    @staticmethod
    def current() -> "IOLoop":
        pass

    @typing.overload
    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        pass

    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        """Returns the current thread's `IOLoop`.

        If an `IOLoop` is currently running or has been marked as
        current by `make_current`, returns that instance.  If there is
        no current `IOLoop` and ``instance`` is true, creates one.

        .. versionchanged:: 4.1
           Added ``instance`` argument to control the fallback to
           `IOLoop.instance()`.
        .. versionchanged:: 5.0
           On Python 3, control of the current `IOLoop` is delegated
           to `asyncio`, with this and other methods as pass-through accessors.
           The ``instance`` argument now controls whether an `IOLoop`
           is created automatically when there is none, instead of
           whether we fall back to `IOLoop.instance()` (which is now
           an alias for this method). ``instance=False`` is deprecated,
           since even if we do not create an `IOLoop`, this method
           may initialize the asyncio loop.

        .. deprecated:: 6.2
           It is deprecated to call ``IOLoop.current()`` when no `asyncio`
           event loop is running.
        """
        try:
            loop = asyncio.get_event_loop()
        except RuntimeError:
            if not instance:
                return None
            # Create a new asyncio event loop for this thread.
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

        try:
            return IOLoop._ioloop_for_asyncio[loop]
        except KeyError:
            if instance:
                from tornado.platform.asyncio import AsyncIOMainLoop

                current = AsyncIOMainLoop()  # type: Optional[IOLoop]
            else:
                current = None
        return current

    def make_current(self) -> None:
        """Makes this the `IOLoop` for the current thread.

        An `IOLoop` automatically becomes current for its thread
        when it is started, but it is sometimes useful to call
        `make_current` explicitly before starting the `IOLoop`,
        so that code run at startup time can find the right
        instance.

        .. versionchanged:: 4.1
           An `IOLoop` created while there is no current `IOLoop`
           will automatically become current.

        .. versionchanged:: 5.0
           This method also sets the current `asyncio` event loop.

        .. deprecated:: 6.2
           Setting and clearing the current event loop through Tornado is
           deprecated. Use ``asyncio.set_event_loop`` instead if you need this.
        """
        warnings.warn(
            "make_current is deprecated; start the event loop first",
            DeprecationWarning,
            stacklevel=2,
        )
        self._make_current()

    def _make_current(self) -> None:
        # The asyncio event loops override this method.
        raise NotImplementedError()

    @staticmethod
    def clear_current() -> None:
        """Clears the `IOLoop` for the current thread.

        Intended primarily for use by test frameworks in between tests.

        .. versionchanged:: 5.0
           This method also clears the current `asyncio` event loop.
        .. deprecated:: 6.2
        """
        warnings.warn(
            "clear_current is deprecated",
            DeprecationWarning,
            stacklevel=2,
        )
        IOLoop._clear_current()

    @staticmethod
    def _clear_current() -> None:
        old = IOLoop.current(instance=False)
        if old is not None:
            old._clear_current_hook()

    def _clear_current_hook(self) -> None:
        """Instance method called when an IOLoop ceases to be current.

        May be overridden by subclasses as a counterpart to make_current.
        """
        pass

    @classmethod
    def configurable_base(cls) -> Type[Configurable]:
        return IOLoop

    @classmethod
    def configurable_default(cls) -> Type[Configurable]:
        from tornado.platform.asyncio import AsyncIOLoop

        return AsyncIOLoop

    def initialize(self, make_current: bool = True) -> None:
        if make_current:
            self._make_current()

    def close(self, all_fds: bool = False) -> None:
        """Closes the `IOLoop`, freeing any resources used.

        If ``all_fds`` is true, all file descriptors registered on the
        IOLoop will be closed (not just the ones created by the
        `IOLoop` itself).

        Many applications will only use a single `IOLoop` that runs for the
        entire lifetime of the process.  In that case closing the `IOLoop`
        is not necessary since everything will be cleaned up when the
        process exits.  `IOLoop.close` is provided mainly for scenarios
        such as unit tests, which create and destroy a large number of
        ``IOLoops``.

        An `IOLoop` must be completely stopped before it can be closed.  This
        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must
        be allowed to return before attempting to call `IOLoop.close()`.
        Therefore the call to `close` will usually appear just after
        the call to `start` rather than near the call to `stop`.

        .. versionchanged:: 3.1
           If the `IOLoop` implementation supports non-integer objects
           for "file descriptors", those objects will have their
           ``close`` method when ``all_fds`` is true.
        """
        raise NotImplementedError()

    @typing.overload
    def add_handler(
        self, fd: int, handler: Callable[[int, int], None], events: int
    ) -> None:
        pass

    @typing.overload  # noqa: F811
    def add_handler(
        self, fd: _S, handler: Callable[[_S, int], None], events: int
    ) -> None:
        pass

    def add_handler(  # noqa: F811
        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
    ) -> None:
        """Registers the given handler to receive the given events for ``fd``.

        The ``fd`` argument may either be an integer file descriptor or
        a file-like object with a ``fileno()`` and ``close()`` method.

        The ``events`` argument is a bitwise or of the constants
        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.

        When an event occurs, ``handler(fd, events)`` will be run.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:
        """Changes the events we listen for ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def remove_handler(self, fd: Union[int, _Selectable]) -> None:
        """Stop listening for events on ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def start(self) -> None:
        """Starts the I/O loop.

        The loop will run until one of the callbacks calls `stop()`, which
        will make the loop stop after the current event iteration completes.
        """
        raise NotImplementedError()

    def stop(self) -> None:
        """Stop the I/O loop.

        If the event loop is not currently running, the next call to `start()`
        will return immediately.

        Note that even after `stop` has been called, the `IOLoop` is not
        completely stopped until `IOLoop.start` has also returned.
        Some work that was scheduled before the call to `stop` may still
        be run before the `IOLoop` shuts down.
        """
        raise NotImplementedError()

    def run_sync(self, func: Callable, timeout: Optional[float] = None) -> Any:
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either an awaitable object or
        ``None``. If the function returns an awaitable object, the
        `IOLoop` will run until the awaitable is resolved (and
        `run_sync()` will return the awaitable's result). If it raises
        an exception, the `IOLoop` will stop and the exception will be
        re-raised to the caller.

        The keyword-only argument ``timeout`` may be used to set
        a maximum duration for the function.  If the timeout expires,
        a `asyncio.TimeoutError` is raised.

        This method is useful to allow asynchronous calls in a
        ``main()`` function::

            async def main():
                # do stuff...

            if __name__ == '__main__':
                IOLoop.current().run_sync(main)

        .. versionchanged:: 4.3
           Returning a non-``None``, non-awaitable value is now an error.

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.

        .. versionchanged:: 6.2
           ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``.
        """
        future_cell = [None]  # type: List[Optional[Future]]

        def run() -> None:
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded

                    result = convert_yielded(result)
            except Exception:
                fut = Future()  # type: Future[Any]
                future_cell[0] = fut
                future_set_exc_info(fut, sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    fut = Future()
                    future_cell[0] = fut
                    fut.set_result(result)
            assert future_cell[0] is not None
            self.add_future(future_cell[0], lambda future: self.stop())

        self.add_callback(run)
        if timeout is not None:

            def timeout_callback() -> None:
                # If we can cancel the future, do so and wait on it. If not,
                # Just stop the loop and return with the task still pending.
                # (If we neither cancel nor wait for the task, a warning
                # will be logged).
                assert future_cell[0] is not None
                if not future_cell[0].cancel():
                    self.stop()

            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
        self.start()
        if timeout is not None:
            self.remove_timeout(timeout_handle)
        assert future_cell[0] is not None
        if future_cell[0].cancelled() or not future_cell[0].done():
            raise TimeoutError("Operation timed out after %s seconds" % timeout)
        return future_cell[0].result()

    def time(self) -> float:
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        Historically, the IOLoop could be customized to use e.g.
        `time.monotonic` instead of `time.time`, but this is not
        currently supported and so this method is equivalent to
        `time.time`.

        """
        return time.time()

    def add_timeout(
        self,
        deadline: Union[float, datetime.timedelta],
        callback: Callable,
        *args: Any,
        **kwargs: Any
    ) -> object:
        """Runs the ``callback`` at the time ``deadline`` from the I/O loop.

        Returns an opaque handle that may be passed to
        `remove_timeout` to cancel.

        ``deadline`` may be a number denoting a time (on the same
        scale as `IOLoop.time`, normally `time.time`), or a
        `datetime.timedelta` object for a deadline relative to the
        current time.  Since Tornado 4.0, `call_later` is a more
        convenient alternative for the relative case since it does not
        require a timedelta object.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        `IOLoop`'s thread, and then call `add_timeout` from there.

        Subclasses of IOLoop must implement either `add_timeout` or
        `call_at`; the default implementations of each will call
        the other.  `call_at` is usually easier to implement, but
        subclasses that wish to maintain compatibility with Tornado
        versions prior to 4.0 must use `add_timeout` instead.

        .. versionchanged:: 4.0
           Now passes through ``*args`` and ``**kwargs`` to the callback.
        """
        if isinstance(deadline, numbers.Real):
            return self.call_at(deadline, callback, *args, **kwargs)
        elif isinstance(deadline, datetime.timedelta):
            return self.call_at(
                self.time() + deadline.total_seconds(), callback, *args, **kwargs
            )
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(
        self, delay: float, callback: Callable, *args: Any, **kwargs: Any
    ) -> object:
        """Runs the ``callback`` after ``delay`` seconds have passed.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.call_at(self.time() + delay, callback, *args, **kwargs)

    def call_at(
        self, when: float, callback: Callable, *args: Any, **kwargs: Any
    ) -> object:
        """Runs the ``callback`` at the absolute time designated by ``when``.

        ``when`` must be a number using the same reference point as
        `IOLoop.time`.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.add_timeout(when, callback, *args, **kwargs)

    def remove_timeout(self, timeout: object) -> None:
        """Cancels a pending timeout.

        The argument is a handle as returned by `add_timeout`.  It is
        safe to call `remove_timeout` even if the callback has already
        been run.
        """
        raise NotImplementedError()

    def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
        """Calls the given callback on the next I/O loop iteration.

        It is safe to call this method from any thread at any time,
        except from a signal handler.  Note that this is the **only**
        method in `IOLoop` that makes this thread-safety guarantee; all
        other interaction with the `IOLoop` must be done from that
        `IOLoop`'s thread.  `add_callback()` may be used to transfer
        control from other threads to the `IOLoop`'s thread.
        """
        raise NotImplementedError()

    def add_callback_from_signal(
        self, callback: Callable, *args: Any, **kwargs: Any
    ) -> None:
        """Calls the given callback on the next I/O loop iteration.

        Intended to be afe for use from a Python signal handler; should not be
        used otherwise.

        .. deprecated:: 6.4
           Use ``asyncio.AbstractEventLoop.add_signal_handler`` instead.
           This method is suspected to have been broken since Tornado 5.0 and
           will be removed in version 7.0.
        """
        raise NotImplementedError()

    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
        """Calls the given callback on the next IOLoop iteration.

        As of Tornado 6.0, this method is equivalent to `add_callback`.

        .. versionadded:: 4.0
        """
        self.add_callback(callback, *args, **kwargs)

    def add_future(
        self,
        future: "Union[Future[_T], concurrent.futures.Future[_T]]",
        callback: Callable[["Future[_T]"], None],
    ) -> None:
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.

        This method only accepts `.Future` objects and not other
        awaitables (unlike most of Tornado where the two are
        interchangeable).
        """
        if isinstance(future, Future):
            # Note that we specifically do not want the inline behavior of
            # tornado.concurrent.future_add_done_callback. We always want
            # this callback scheduled on the next IOLoop iteration (which
            # asyncio.Future always does).
            #
            # Wrap the callback in self._run_callback so we control
            # the error logging (i.e. it goes to tornado.log.app_log
            # instead of asyncio's log).
            future.add_done_callback(
                lambda f: self._run_callback(functools.partial(callback, future))
            )
        else:
            assert is_future(future)
            # For concurrent futures, we use self.add_callback, so
            # it's fine if future_add_done_callback inlines that call.
            future_add_done_callback(
                future, lambda f: self.add_callback(callback, future)
            )

    def run_in_executor(
        self,
        executor: Optional[concurrent.futures.Executor],
        func: Callable[..., _T],
        *args: Any
    ) -> "Future[_T]":
        """Runs a function in a ``concurrent.futures.Executor``. If
        ``executor`` is ``None``, the IO loop's default executor will be used.

        Use `functools.partial` to pass keyword arguments to ``func``.

        .. versionadded:: 5.0
        """
        if executor is None:
            if not hasattr(self, "_executor"):
                from tornado.process import cpu_count

                self._executor = concurrent.futures.ThreadPoolExecutor(
                    max_workers=(cpu_count() * 5)
                )  # type: concurrent.futures.Executor
            executor = self._executor
        c_future = executor.submit(func, *args)
        # Concurrent Futures are not usable with await. Wrap this in a
        # Tornado Future instead, using self.add_future for thread-safety.
        t_future = Future()  # type: Future[_T]
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
        """Sets the default executor to use with :meth:`run_in_executor`.

        .. versionadded:: 5.0
        """
        self._executor = executor

    def _run_callback(self, callback: Callable[[], Any]) -> None:
        """Runs a callback with error handling.

        .. versionchanged:: 6.0

           CancelledErrors are no longer logged.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen

                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, self._discard_future_result)
        except asyncio.CancelledError:
            pass
        except Exception:
            app_log.error("Exception in callback %r", callback, exc_info=True)

    def _discard_future_result(self, future: Future) -> None:
        """Avoid unhandled-exception warnings from spawned coroutines."""
        future.result()

    def split_fd(
        self, fd: Union[int, _Selectable]
    ) -> Tuple[int, Union[int, _Selectable]]:
        # """Returns an (fd, obj) pair from an ``fd`` parameter.

        # We accept both raw file descriptors and file-like objects as
        # input to `add_handler` and related methods.  When a file-like
        # object is passed, we must retain the object itself so we can
        # close it correctly when the `IOLoop` shuts down, but the
        # poller interfaces favor file descriptors (they will accept
        # file-like objects and call ``fileno()`` for you, but they
        # always return the descriptor itself).

        # This method is provided for use by `IOLoop` subclasses and should
        # not generally be used by application code.

        # .. versionadded:: 4.0
        # """
        if isinstance(fd, int):
            return fd, fd
        return fd.fileno(), fd

    def close_fd(self, fd: Union[int, _Selectable]) -> None:
        # """Utility method to close an ``fd``.

        # If ``fd`` is a file-like object, we close it directly; otherwise
        # we use `os.close`.

        # This method is provided for use by `IOLoop` subclasses (in
        # implementations of ``IOLoop.close(all_fds=True)`` and should
        # not generally be used by application code.

        # .. versionadded:: 4.0
        # """
        try:
            if isinstance(fd, int):
                os.close(fd)
            else:
                fd.close()
        except OSError:
            pass

    def _register_task(self, f: Future) -> None:
        self._pending_tasks.add(f)

    def _unregister_task(self, f: Future) -> None:
        self._pending_tasks.discard(f)


class _Timeout(object):
    """An IOLoop timeout, a UNIX timestamp and a callback"""

    # Reduce memory overhead when there are lots of pending callbacks
    __slots__ = ["deadline", "callback", "tdeadline"]

    def __init__(
        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (
            deadline,
            next(io_loop._timeout_counter),
        )  # type: Tuple[float, int]

    # Comparison methods to sort by deadline, with object id as a tiebreaker
    # to guarantee a consistent ordering.  The heapq module uses __le__
    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
    # use __lt__).
    def __lt__(self, other: "_Timeout") -> bool:
        return self.tdeadline < other.tdeadline

    def __le__(self, other: "_Timeout") -> bool:
        return self.tdeadline <= other.tdeadline


class PeriodicCallback(object):
    """Schedules the given callback to be called periodically.

    The callback is called every ``callback_time`` milliseconds when
    ``callback_time`` is a float. Note that the timeout is given in
    milliseconds, while most other time-related functions in Tornado use
    seconds. ``callback_time`` may alternatively be given as a
    `datetime.timedelta` object.

    If ``jitter`` is specified, each callback time will be randomly selected
    within a window of ``jitter * callback_time`` milliseconds.
    Jitter can be used to reduce alignment of events with similar periods.
    A jitter of 0.1 means allowing a 10% variation in callback time.
    The window is centered on ``callback_time`` so the total number of calls
    within a given interval should not be significantly affected by adding
    jitter.

    If the callback runs for longer than ``callback_time`` milliseconds,
    subsequent invocations will be skipped to get back on schedule.

    `start` must be called after the `PeriodicCallback` is created.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.1
       The ``jitter`` argument is added.

    .. versionchanged:: 6.2
       If the ``callback`` argument is a coroutine, and a callback runs for
       longer than ``callback_time``, subsequent invocations will be skipped.
       Previously this was only true for regular functions, not coroutines,
       which were "fire-and-forget" for `PeriodicCallback`.

       The ``callback_time`` argument now accepts `datetime.timedelta` objects,
       in addition to the previous numeric milliseconds.
    """

    def __init__(
        self,
        callback: Callable[[], Optional[Awaitable]],
        callback_time: Union[datetime.timedelta, float],
        jitter: float = 0,
    ) -> None:
        self.callback = callback
        if isinstance(callback_time, datetime.timedelta):
            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)
        else:
            if callback_time <= 0:
                raise ValueError("Periodic callback must have a positive callback_time")
            self.callback_time = callback_time
        self.jitter = jitter
        self._running = False
        self._timeout = None  # type: object

    def start(self) -> None:
        """Starts the timer."""
        # Looking up the IOLoop here allows to first instantiate the
        # PeriodicCallback in another thread, then start it using
        # IOLoop.add_callback().
        self.io_loop = IOLoop.current()
        self._running = True
        self._next_timeout = self.io_loop.time()
        self._schedule_next()

    def stop(self) -> None:
        """Stops the timer."""
        self._running = False
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def is_running(self) -> bool:
        """Returns ``True`` if this `.PeriodicCallback` has been started.

        .. versionadded:: 4.1
        """
        return self._running

    async def _run(self) -> None:
        if not self._running:
            return
        try:
            val = self.callback()
            if val is not None and isawaitable(val):
                await val
        except Exception:
            app_log.error("Exception in callback %r", self.callback, exc_info=True)
        finally:
            self._schedule_next()

    def _schedule_next(self) -> None:
        if self._running:
            self._update_next(self.io_loop.time())
            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)

    def _update_next(self, current_time: float) -> None:
        callback_time_sec = self.callback_time / 1000.0
        if self.jitter:
            # apply jitter fraction
            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
        if self._next_timeout <= current_time:
            # The period should be measured from the start of one call
            # to the start of the next. If one call takes too long,
            # skip cycles to get back to a multiple of the original
            # schedule.
            self._next_timeout += (
                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1
            ) * callback_time_sec
        else:
            # If the clock moved backwards, ensure we advance the next
            # timeout instead of recomputing the same value again.
            # This may result in long gaps between callbacks if the
            # clock jumps backwards by a lot, but the far more common
            # scenario is a small NTP adjustment that should just be
            # ignored.
            #
            # Note that on some systems if time.time() runs slower
            # than time.monotonic() (most common on windows), we
            # effectively experience a small backwards time jump on
            # every iteration because PeriodicCallback uses
            # time.time() while asyncio schedules callbacks using
            # time.monotonic().
            # https://github.com/tornadoweb/tornado/issues/2333
            self._next_timeout += callback_time_sec

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