diff --git a/tests/core/utilities/test_http_session_manager.py b/tests/core/utilities/test_http_session_manager.py index 1621c5f5f1..d08859fea3 100644 --- a/tests/core/utilities/test_http_session_manager.py +++ b/tests/core/utilities/test_http_session_manager.py @@ -455,12 +455,14 @@ async def cache_uri_and_return_session(uri): # last session remains in cache, all others evicted cache_data = http_session_manager.session_cache._data assert len(cache_data) == 1 + assert len(http_session_manager.aiohttp_evicted_sessions) == 1 _key, cached_session = cache_data.popitem() assert cached_session == all_sessions[-1] # assert all evicted sessions were closed await asyncio.sleep(_timeout_for_testing + 0.1) assert all(session.closed for session in all_sessions[:-1]) + assert len(http_session_manager.aiohttp_evicted_sessions) == 0 # -- teardown -- # diff --git a/web3/_utils/http_session_manager.py b/web3/_utils/http_session_manager.py index 913ea550f1..9fc96eca72 100644 --- a/web3/_utils/http_session_manager.py +++ b/web3/_utils/http_session_manager.py @@ -51,6 +51,7 @@ def __init__( self.session_cache = SimpleCache(cache_size) self.session_pool = ThreadPoolExecutor(max_workers=session_pool_max_workers) self._explicit_session = explicit_session + self.aiohttp_evicted_sessions: set[ClientSession] = set() @staticmethod def get_default_http_endpoint() -> URI: @@ -252,6 +253,7 @@ async def async_cache_and_return_session( # just stored in the `evicted_sessions` dict. So we can kick off a future # task to close them and it should be safe to pop out of the lock here. evicted_sessions = list(evicted_items.values()) + self.aiohttp_evicted_sessions.update(evicted_sessions) for evicted_session in evicted_sessions: self.logger.debug( "Async session cache full. Session evicted from cache: %s", @@ -329,6 +331,7 @@ async def _async_close_evicted_sessions( for evicted_session in evicted_sessions: await evicted_session.close() + self.aiohttp_evicted_sessions.remove(evicted_session) self.logger.debug("Closed evicted async session: %s", evicted_session) if any(not evicted_session.closed for evicted_session in evicted_sessions):