fix: make AgentGraph destructor loop-safe to prevent connection leaks#147
Open
bhavyakeerthi3 wants to merge 1 commit intoreactome:mainfrom
Open
fix: make AgentGraph destructor loop-safe to prevent connection leaks#147bhavyakeerthi3 wants to merge 1 commit intoreactome:mainfrom
bhavyakeerthi3 wants to merge 1 commit intoreactome:mainfrom
Conversation
75090ff to
b9de69b
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The
AgentGraphdestructor (__del__) currently callsasyncio.run(self.close_pool()). In an asynchronous environment (like a Chainlit or FastAPI server), if the agent instance is deleted while an event loop is already running,asyncio.run()raises aRuntimeError: This event loop is already running. Because the destructor fails mid-execution, the connection pool is never closed, leading to hanging database connections and potential pool exhaustion.Fix #146
Updated the destructor to be loop-aware. It now checks for a running event loop and schedules the cleanup task using
loop.create_task()instead of attempting to start a new nested loop.Important
loop.create_task()during__del__is best-effort. If the eventloop closes before the task executes, cleanup may still be skipped.
The robust long-term solution is explicit lifecycle management via a
shutdown()method, but this fix resolves the immediateRuntimeErrorand improves reliability during server reloads.Verification
Verified with a standalone validation script covering two scenarios:
close_poolis scheduled as a task when a loop is running.asyncio.runis used as a fallback when no loop is present (e.g., script exit).Files Affected
src/agent/graph.py