azure-sdk-for-python icon indicating copy to clipboard operation
azure-sdk-for-python copied to clipboard

Event loop closed when running async point queries

Open gahl-levy opened this issue 4 years ago • 2 comments

-Windows 11 -Python 3.9.1

I'm getting RuntimeErrors every time I try to run async io sample code because the event loop is closed. The only way I've found to fix this on my machine is by changing the default event loop policy to the selector policy:

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

To Reproduce Run this sample code with your db account:

# Import async client
import asyncio
from azure.cosmos.aio import CosmosClient

# Access credentials 
url = os.environ['ACCOUNT_URI']
key = os.environ['ACCOUNT_KEY']

# Client initialization  
client = CosmosClient(url, credential=key)

# To run, replace database and container with your db and container names
database = client.get_database_client("ToDoList")
container = database.get_container_client("test")

async def point_read(item):
    # Point Read
    data = await container.read_item(item=item, partition_key=item)
    return data

async def read():
    results = container.query_items(
            query='SELECT * FROM ToDoList.test')
    item_list = [item async for item in results]
    print(item_list)

            
async def main():
    # To run, change item1 item2 and item3 to each document's id 
    print(await asyncio.gather(point_read("test1"), point_read("test2"), point_read("test3")))
    await client.close()

#asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

Get this error (it seems like the operation still completes regardless):

python .\test_samples.py
[{'id': 'test1', '_rid': 'rm1+AO1M6SgBAAAAAAAAAA==', '_self': 'dbs/rm1+AA==/colls/rm1+AO1M6Sg=/docs/rm1+AO1M6SgBAAAAAAAAAA==/', '_etag': '"00000a00-0000-0100-0000-61afe6360000"', '_attachments': 'attachments/', '_ts': 1638917686}, {'id': 'test2', '_rid': 'rm1+AO1M6SgCAAAAAAAAAA==', '_self': 'dbs/rm1+AA==/colls/rm1+AO1M6Sg=/docs/rm1+AO1M6SgCAAAAAAAAAA==/', '_etag': '"00000b00-0000-0100-0000-61afe63e0000"', '_attachments': 'attachments/', '_ts': 1638917694}, {'id': 'test3', '_rid': 'rm1+AO1M6SgDAAAAAAAAAA==', '_self': 'dbs/rm1+AA==/colls/rm1+AO1M6Sg=/docs/rm1+AO1M6SgDAAAAAAAAAA==/', '_etag': '"00000c00-0000-0100-0000-61afe6430000"', '_attachments': 'attachments/', '_ts': 1638917699}]
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000023959B1EA60>
Traceback (most recent call last):
  File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000023959B1EA60>
Traceback (most recent call last):
  File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000023959B1EA60>
Traceback (most recent call last):
  File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

gahl-levy avatar Dec 08 '21 14:12 gahl-levy

I'll add that I have 2 environments I typically test in:

(env 1) Windows / VS Code / bash / Python 3.9.5 in a virtual environment (env 2) Ubuntu / WSL / bash / Python 3.8.10 in a virtual environment

The Cosmos code sample works in Windows environment (env 1) but returns "RuntimeError: Event loop is closed". The same code doesn't throw the error in Ubuntu (env 2). Is this related to https://github.com/encode/httpx/issues/914? I noticed using code similar to the snippet below for service bus or event hubs works in both environments with no error.

Sample code to return event loop error.


import os
import asyncio
from azure.cosmos.aio import CosmosClient

ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]

async def manage_cosmos():
    async with CosmosClient(url=ENDPOINT, credential=KEY) as client:
        print("Client created")
        # Some code here

asyncio.run(manage_cosmos())

vmagelo avatar Jan 26 '23 14:01 vmagelo

Hi @gahl-levy, we deeply appreciate your input into this project. Regrettably, this issue has remained inactive for over 2 years, leading us to the decision to close it. We've implemented this policy to maintain the relevance of our issue queue and facilitate easier navigation for new contributors. If you still believe this topic requires attention, please feel free to create a new issue, referencing this one. Thank you for your understanding and ongoing support.

github-actions[bot] avatar Mar 13 '24 18:03 github-actions[bot]