Skip to content

Commit 9661a37

Browse files
authored
Merge pull request #2654 from opentensor/fix/thewhaleking/dendrite-loop-close
Fixes Dendrite new loop close
2 parents d9275ed + c944235 commit 9661a37

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

bittensor/core/dendrite.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,18 @@ async def session(self) -> aiohttp.ClientSession:
163163
self._session = aiohttp.ClientSession()
164164
return self._session
165165

166-
def close_session(self):
166+
def close_session(self, using_new_loop: bool = False):
167167
"""
168168
Closes the internal `aiohttp <https://github.com/aio-libs/aiohttp>`_ client session synchronously.
169169
170170
This method ensures the proper closure and cleanup of the aiohttp client session, releasing any
171171
resources like open connections and internal buffers. It is crucial for preventing resource leakage
172172
and should be called when the dendrite instance is no longer in use, especially in synchronous contexts.
173173
174+
Arguments:
175+
using_new_loop: A flag to determine whether this has been called with a new event loop rather than
176+
the default. This will indicate whether to close this event loop at the end of this call.
177+
174178
Note:
175179
This method utilizes asyncio's event loop to close the session asynchronously from a synchronous context.
176180
It is advisable to use this method only when asynchronous context management is not feasible.
@@ -188,6 +192,8 @@ def close_session(self):
188192
if self._session:
189193
loop = asyncio.get_event_loop()
190194
loop.run_until_complete(self._session.close())
195+
if using_new_loop:
196+
loop.close()
191197
self._session = None
192198

193199
async def aclose_session(self):
@@ -374,16 +380,20 @@ def query(
374380
category=DeprecationWarning,
375381
)
376382
result = None
383+
use_new_loop = False
377384
try:
378385
loop = asyncio.get_event_loop()
379386
result = loop.run_until_complete(self.forward(*args, **kwargs))
380-
except Exception:
387+
except Exception as e:
388+
logging.debug(
389+
f"Exception encountered while running Dendrite.query initially: {e}"
390+
)
381391
new_loop = asyncio.new_event_loop()
382392
asyncio.set_event_loop(new_loop)
383393
result = new_loop.run_until_complete(self.forward(*args, **kwargs))
384-
new_loop.close()
394+
use_new_loop = True
385395
finally:
386-
self.close_session()
396+
self.close_session(using_new_loop=use_new_loop)
387397
return result # type: ignore
388398

389399
async def forward(

0 commit comments

Comments
 (0)