{"record":{"id":"9e76dddd7d7c6439","repo":"pola-rs/polars","slug":"event-loop-stopped-before-future-completed","errorCode":null,"errorMessage":"Event loop stopped before Future completed.","messagePattern":"Event loop stopped before Future completed\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/nest_asyncio.py","lineNumber":283,"sourceCode":"    def run_forever(self):\n        with manage_run(self), manage_asyncgens(self):\n            while True:\n                self._run_once()\n                if self._stopping:\n                    break\n        self._stopping = False\n\n    def run_until_complete(self, future):\n        with manage_run(self):\n            f = asyncio.ensure_future(future, loop=self)\n            if f is not future:\n                f._log_destroy_pending = False\n            while not f.done():\n                self._run_once()\n                if self._stopping:\n                    break\n            if not f.done():\n                raise RuntimeError(\"Event loop stopped before Future completed.\")\n            return f.result()\n\n    def _run_once(self):\n        \"\"\"\n        Simplified re-implementation of asyncio's _run_once that\n        runs handles as they become ready.\n        \"\"\"\n        scheduled = self._scheduled\n        while scheduled and scheduled[0]._cancelled:\n            heappop(scheduled)\n\n        timeout = (\n            0\n            if self._ready or self._stopping\n            else min(max(scheduled[0]._when - self.time(), 0), 86400)\n            if scheduled\n            else None\n        )","sourceCodeStart":265,"sourceCodeEnd":301,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/nest_asyncio.py#L265-L301","documentation":"The patched `run_until_complete` in polars' nest_asyncio runs the loop until the future is done OR the loop is stopping. If the loop was stopped (e.g. by an outer `stop()` or another coroutine stopping the loop) before the awaited future finished, the future is incomplete and RuntimeError is raised.","triggerScenarios":"Calling a polars API that internally runs `loop.run_until_complete(fut)` inside an environment where something else stops the event loop — e.g. nesting `run_until_complete` inside an already-running loop, a signal handler calling `loop.stop()`, or cancelled tasks.","commonSituations":"Jupyter notebooks with competing event-loop managers; mixing polars' patched loop with other frameworks (tornado, ipykernel) that stop loops; calling async-blocking polars helpers from threads.","solutions":["Run the coroutine on a fresh event loop instead of a shared/stopped one: `asyncio.run(coro)` in a clean context.","Avoid nesting `run_until_complete` calls; restructure code to `await` instead.","Ensure nothing calls `loop.stop()` before the future completes; check signal handlers and other libraries patching asyncio.","Upgrade polars / remove nest_asyncio patching if running under Jupyter's native async support (Python 3.8+ IPython supports top-level await)."],"exampleFix":"// before\nloop.run_until_complete(coro)  # RuntimeError inside notebook's running loop\n// after\nresult = await coro  # top-level await in Jupyter","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try:\n    result = loop.run_until_complete(fut)\nexcept RuntimeError as e:\n    if \"Event loop stopped before Future completed\" in str(e):\n        result = asyncio.run(coro)  # retry on a fresh loop\n    else:\n        raise","preventionTips":["Never call `loop.stop()` while awaited futures are pending.","Avoid nested `run_until_complete` calls; use `await`.","In Jupyter, use top-level `await` instead of manually driving loops.","Run blocking async helpers on a dedicated, single-owner event loop."],"tags":["polars","asyncio","event-loop","runtimeerror"],"backgroundTag":"invalid-state-transition","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}