{"record":{"id":"694e09c225e23c20","repo":"docling-project/docling","slug":"this-method-cannot-run-inside-an-active-asyncio-lo","errorCode":null,"errorMessage":"This method cannot run inside an active asyncio loop. Call it from synchronous code.","messagePattern":"This method cannot run inside an active asyncio loop\\. Call it from synchronous code\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"docling/service_client/client.py","lineNumber":2077,"sourceCode":"            # Drive the fan-out through the native async client so the sync batch\n            # API runs concurrently on a private event loop without threads.\n            async with self._build_async_service_client() as async_client:\n                async for outcome in async_client.submit_and_retrieve_each(\n                    items=item_list,\n                    max_in_flight=max_in_flight,\n                    ordered=ordered,\n                    target=target,\n                ):\n                    yield outcome\n\n        return self._iterate_async_generator_sync(run())\n\n    def _ensure_sync_bridge_allowed(self) -> None:\n        try:\n            asyncio.get_running_loop()\n        except RuntimeError:\n            return\n        raise RuntimeError(\n            \"This method cannot run inside an active asyncio loop. \"\n            \"Call it from synchronous code.\"\n        )\n\n    def _iterate_async_generator_sync(\n        self, async_iterator: AsyncGenerator[_T, None]\n    ) -> Iterator[_T]:\n        loop = asyncio.new_event_loop()\n\n        def iterator() -> Iterator[_T]:\n            try:\n                asyncio.set_event_loop(loop)\n                while True:\n                    try:\n                        yield loop.run_until_complete(anext(async_iterator))\n                    except StopAsyncIteration:\n                        break\n            finally:","sourceCodeStart":2059,"sourceCodeEnd":2095,"githubUrl":"https://github.com/docling-project/docling/blob/61d76f1ff3f8428065465889f7b4577da7df704c/docling/service_client/client.py#L2059-L2095","documentation":"RuntimeError raised by _ensure_sync_bridge_allowed when a synchronous API (e.g. sync convert_all iteration or other sync wrappers that bridge async generators via a private event loop) is called from inside a running asyncio loop. Bridging would deadlock the loop, so the client refuses.","triggerScenarios":"Calling the sync iteration path (methods that call _iterate_async_generator_sync) from inside 'async def' code or a Jupyter cell, where asyncio.get_running_loop() succeeds.","commonSituations":"Using sync client methods inside Jupyter notebooks (which run a loop), FastAPI handlers, or any async framework; mixing sync/async client styles in one codebase.","solutions":["Use the async API instead: await client.async_convert(...) / the async equivalents inside async code","In scripts, keep sync calls in plain functions with no running loop","In Jupyter, run sync calls in a separate thread or switch to the async client"],"exampleFix":"# before\nasync def handle():\n    for res in client.convert_all(sources):  # RuntimeError\n        ...\n\n# after\nasync def handle():\n    async for res in client.async_convert_all(sources):\n        ...","handlingStrategy":"type-guard","validationCode":"import asyncio\n\ndef in_async_context() -> bool:\n    try:\n        asyncio.get_running_loop()\n        return True\n    except RuntimeError:\n        return False\n\n# assert not in_async_context() before calling sync client methods","typeGuard":"def in_async_context() -> bool:\n    try:\n        asyncio.get_running_loop()\n        return True\n    except RuntimeError:\n        return False","tryCatchPattern":"try:\n    sync_call()\nexcept RuntimeError as exc:\n    if 'cannot run inside an active asyncio loop' in str(exc):\n        switch_to_async_api()","preventionTips":["Standardize on the async client inside async frameworks and Jupyter","Guard sync entry points with asyncio.get_running_loop() checks in mixed codebases"],"tags":["asyncio","api-misuse","runtime-error"],"backgroundTag":null,"analyzedSha":"61d76f1ff3f8428065465889f7b4577da7df704c","analyzedAt":"2026-08-14T23:53:18.727Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}